I have a form which the user inputs a file name into. It iterates through all the directories successfully looking to match the users search input to the relevant pdf file.
When it finds the match it correctly echos 'it matches' and breaks out of the foreach loop. However, it also correctly states 'not a match' for all the files it finds before it matches the correct file. So I get a long list of 'not a match ' followed by 'it matches'.
If I echo " " instead of 'not a match' it works fine and doesn't display anything but I would like to tell the user only once that what they have inputted does not match. I am sure I have overlooked something basic but any assistance would be greatly appreciated on how to achieve this.
Here is the code I have.
<?php
if (isset($_POST['submit']) && !empty($_POST['target'])) {
$searchInput = $_POST['target'];
$it = new RecursiveDirectoryIterator("/myDirectory/");
foreach(new RecursiveIteratorIterator($it) as $file) {
$path_info = pathinfo($file);
$extension = $path_info['extension'];
if (strcmp("pdf", $extension) == 0) {
$lowerInput = strtolower($searchInput);
if (!empty($path_info)) {
$string = strtolower($path_info['filename']);
if(preg_match("~\b" . $lowerInput. "\b~", $string)) {
echo "it matches <br>";
break;
} else {
if (!preg_match("~\b" . $lowerInput . "\b~", $string)) {
echo "not a match <br>";
}
}
}
}
} //end foreach
} // end if submit pressed
?>
<html>
<head>
</head>
<body>
<h3>Search Files</h3>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="searchform">
Type the File You Require:<br><br>
<input id="target" type="text" name="target" required >
<br>
<input id="submit" type="submit" name="submit" value="Search" >
</form>
</body>
</html>
I've left out some of your code, just showing the parts that matter. Basically just set a variable and echo it once when the foreach completes.
$msg="Not a match <br>" ;
foreach(new RecursiveIteratorIterator($it) as $file) {
...
if(preg_match("~\b" . $lowerInput. "\b~", $string)) {
$msg = "it matches <br>" ;
break ;
}
// no need for an else clause, "not a match" is default finding
}// end of foreach
echo $msg ;
Related
We need to create a program that lets the user input the array size, their name, and age (depending on the array size the user entered). After that, we need to display all the elements of the array.
This is my code, but I'm having a problem adding a new element for another user and displaying it.
<html>
<head>
<title> PHP Array </title>
</head>
<body>
<form method="post" action="example.php">
<h3> Please enter the your information: </h3>
Array Size: <input type="text" name="arraysize"/> <br/><br>
Name: <input type="text" name="name" /><br/><br/>
Age: <input type="text" name="age"/> <br/><br/>
<input type="submit" name="submit" value="Submit"/>
<input type="reset" name="cancel" value="Cancel"/><br/><br/>
<?php
if(isset($_POST['submit'])){
if((!empty($_POST['name'])) && (!empty($_POST['age'])) && (!empty($_POST['arraysize']))){
$info = array($_POST['arraysize'], $_POST['name'], $_POST['g6ave']);
$arraylength = count($info);
for ($i=0; $i<=$arraylength ; $i++) {
$name = $_POST['name'];
for ($j=1; $j<=$i; $j++){
echo "User's Name" .$i. ": " .$name. [$j] ."<br>";
$age = $_POST['age'];
for($k=0; $k<=$i; $k++){
echo "User's Age: " .$age. [$k] ."<br/>";
}
}
}
}
}
?>
</body>
</html>
One approach (of other possible approaches) below should give you the main ideas. I also commented the aim of the each script part.
Approach below assumes that you'll use same URL for all your form pages. (1st, 2nd and the success page)
I hope this helps.
session_start(); //Start new or resume existing session
if (isset($_SESSION['form_success']) && $_SESSION['form_success'] === true)
{
require 'success_page.php';
unset($_SESSION['form_success']); // don't needed anymore
return; //not to continue to execute the code
}
// decide the page from user
if (isset($_POST['page']))
{
$page = $_POST['page'];
}
else
{
// display the first form page for the 1st time
require 'first_page_form.php';
return; //not to continue to execute the code
}
// if the first page was submitted.
if ($page === 'first') // or a specific POST flag from 1st page
{
//verify data from first page
$warnings = [];
if (first_page_data_valid() === true)
{
require 'second_page_form.php';
return; //not to continue to execute the code
}
// populate $warnings during first_page_data_valid()
//if first page data are invalid
print_r($warnings);
require 'first_page_form.php'; //display again
return; //not to continue to execute the code
}
// if the second page was submitted.
if ($page === 'second') // or a specific POST flag from 2nd page
{
//verify data from second page
$warnings = [];
if (second_page_data_valid() === true) // populate $warnings during second_page_data_valid()
{
// do things. ex: DB operations.
if (db_actions_success() === true)
{
$_SESSION['form_success'] = true; // defined and set to true.
// PHP permanent URL redirection. usage of 301 is important.
// it clears POST content. Prevents F5/refresh.
header("Location: https://www.url.com/form.php", true, 301);
exit; // good/recommended to use after redirect
}
else
{
echo 'System down or I have a bug. Try again later.';
return; //not to continue to execute the code
}
}
//if second page data is invalid
print_r($warnings);
require 'second_page_form.php'; //display again
return; //not to continue to execute the code
}
Can someone help me to figure out how to replace a defined string value with user input value? I am quite new in PHP programming and could not find an answer. I saw a lot of ways to replace string on the internet by using built-in functions or in arrays, but I could not find out the right answer to my question.
Here is my code:
$text = "Not found";
if ( isset($_GET['user'])) {
$user_input = $_GET['user'];
}
// from here I I tried to replace the value $text to user input, but it does not work.
$raw = TRUE;
$spec_char = "";
if ($raw) {
$raw = htmlentities($text);
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>"; *# displays "Not found"*
} elseif (!$raw == TRUE ) {
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
I appreciate your answers.
Lets run over your code, line by line.
// Set a default value for $text
$text = "Not found";
// Check if a value has been set...
if (isset($_GET['user'])) {
// But then create a new var with that value.
// Why? Are you going to change it?
$user_input = $_GET['user'];
}
// Define a few vars
$raw = TRUE;
$spec_char = "";
// This next line is useless - Why? Because $raw is always true.
// A better test would be to check for $user_input or do the
// isset() check here instead.
if ($raw) {
// Basic sanity check, but $text is always going to be
// "Not found" - as you have never changed it.
$raw = htmlentities($text);
// render some HTML - but as you said, always going to display
// "Not found"
echo "<p style='font-style:bold;'> PIN " . $raw . "</p>";
} elseif (!$raw == TRUE ) {
// This code is never reached.
$spec_char = htmlspecialchars($user_input);
echo "<p>PIN $spec_char </p>";
}
// I have no idea what this HTML is for really.
// Guessing this is your "input" values.
<form>
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
Just a guess I think you really wanted to do something more like this:
<?php
// Check if a value has been posted...
if (isset($_POST['user'])) {
// render some HTML
echo '<p style="font-style:bold"> PIN '.htmlspecialchars($_POST['user']).'</p>';
}
?>
<form method="post" action="?">
<input type="text" name="user" size="40" />
<input type="submit" value="User_val"/>
</form>
My code should provide two random numbers and have the user enter their product (multiplication).
If you enter a wrong answer, it tells you to guess again, but keeps the same random numbers until you answer correctly. Answer correctly, and it starts over with a new pair of numbers.
The below code changes the value of the two random numbers even if I entered the wrong number. I would like to keep the values the same until the correct answer is entered.
<?php
$num1=rand(1, 9);
$num2=rand(1, 9);
$num3=$num1*$num2;
$num_to_guess = $num3;
echo $num1."x".$num2."= <br>";
if ($_POST['guess'] == $num_to_guess)
{ // matches!
$message = "Well done!";
}
elseif ($_POST['guess'] > $num_to_guess)
{
$message = $_POST['guess']." is too big! Try a smaller number.";
}
elseif ($_POST['guess'] < $num_to_guess)
{
$message = $_POST['guess']." is too small! Try a larger number.";
}
else
{ // some other condition
$message = "I am terribly confused.";
}
?>
<!DOCTYPE html>
<html>
<body>
<h2><?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="answer" value="<?php echo $answer;?>">
<input type="hidden" name="expression" value="<?php echo $expression;?>">
What is the value of the following multiplication expression: <br><br>
<?php echo $expression; ?> <input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
In order to keep the same numbers, you have to store them on the page and then check them when the form is submitted using php. You must also set the random number if the form was never submitted. In your case, you were always changing num1 and num2. I tried to leave as much of your original code intact, but it still needs some work to simplify it.
First I added 2 more hidden field in the html called num1 and num2
Second, I set $num1 and $num2 to the value that was submitted from the form.
After following the rest of the logic, I make sure that $num1 and $num2 are reset if the answer is correct of it the form was never submitted.
You can see the comments in the code below.
Additionally, if you were going to use this in a production environment, you would want to validate the values being passed in from the form so that malicious users don't take advantage of your code. :)
<?php
// Setting $num1 and $num2 to what was posted previously and performing the math on it.
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$num_to_guess = $num1*$num2;
// Check for the correct answer
if ($_POST && $_POST['guess'] == $num_to_guess)
{
// matches!
$message = "Well done!";
$num1=rand(1, 9);
$num2=rand(1, 9);
}
// Give the user a hint that the number is too big
elseif ($_POST['guess'] > $num_to_guess)
{
$message = $_POST['guess']." is too big! Try a smaller number.";
}
// Give the user a hint that the number is too small
elseif ($_POST['guess'] < $num_to_guess)
{
$message = $_POST['guess']." is too small! Try a larger number.";
}
// If the form wasn't submitted i.e. no POST or something else went wrong
else
{
// Only display this message if the form was submitted, but there were no expected values
if ($_POST)
{
// some other condition and only if something was posted
$message = "I am terribly confused.";
}
// set num1 and num2 if there wasn't anything posted
$num1=rand(1, 9);
$num2=rand(1, 9);
}
// Show the problem
echo $num1."x".$num2."= <br>";
?>
<!DOCTYPE html>
<html>
<body>
<h2><?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="num1" value="<?= $num1 ?>" />
<input type="hidden" name="num2" value="<?= $num2 ?>" />
<input type="hidden" name="answer" value="<?php echo $num3;?>">
<input type="hidden" name="expression" value="<?php echo $expression;?>">
What is the value of the following multiplication expression: <br><br>
<input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
When you load the page for the first time, you have (i.e.) “2*3” as question. $_POST is not defined, so if ($_POST['guess']... will produce a undefined index warning. Then you echo $message, but where you define $message? $_POST['guess'] is undefined, so is evaluated as 0, $num_to_guess is 6 (=2*3), so $message is set to " is too small! Try a larger number.", even if the user has not input anything. The hidden answer is set to $answer, but this variable is not defined so it is set to nothing (or to “Notice: Undefined variable: answer”, if you activate error reporting). Same issue for expression input and for echo $expression.
Try something like this:
$newQuestion = True; // This variable to check if a new multiplication is required
$message = '';
/* $_POST['guess'] check only if form is submitted: */
if( isset( $_POST['guess'] ) )
{
/* Comparison with answer, not with new result: */
if( $_POST['guess'] == $_POST['answer'] )
{
$message = "Well done!";
}
else
{
/* If result if wrong, no new question needed, so we propose same question: */
$newQuestion = False;
$answer = $_POST['answer'];
$expression = $_POST['expression'];
if( $_POST['guess'] > $_POST['answer'] )
{
$message = "{$_POST['guess']} is too big! Try a smaller number.";
}
else
{
$message = "{$_POST['guess']} is too small! Try a larger number.";
}
}
}
/* New question is generated only on first page load or if previous answer is ok: */
if( $newQuestion )
{
$num1 = rand( 1, 9 );
$num2 = rand( 1, 9 );
$answer = $num1*$num2;
$expression = "$num1 x $num2";
if( $message ) $message .= "<br>Try a new one:";
else $message = "Try:";
}
?>
<!DOCTYPE html>
(... Your HTML Here ...)
This might also be fun to learn. This is a session. Lets you store something temporarily. It is a little dirty. But fun to learn from.
http://www.w3schools.com/php/php_sessions.asp
<?php
session_start(); // Starts the Session.
function Save() { // Function to save $num1 and $num2 in a Session.
$_SESSION['num1'] = rand(1, 9);
$_SESSION['num2'] = rand(1, 9);
$_SESSION['num_to_guess'] = $_SESSION['num1']*$_SESSION['num2'];;
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// If there is no session set
if (!isset($_SESSION['num_to_guess'])) {
Save();
$message = "";
}
if (isset($_POST['guess'])) {
// Check for the correct answer
if ($_POST['guess'] == $_SESSION['num_to_guess']) {
$message = "Well done!";
session_destroy(); // Destroys the Session.
Save(); // Set new Sessions.
}
// Give the user a hint that the number is too big
elseif ($_POST['guess'] > $_SESSION['num_to_guess']) {
$message = $_POST['guess']." is too big! Try a smaller number.";
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// Give the user a hint that the number is too small
elseif ($_POST['guess'] < $_SESSION['num_to_guess']) {
$message = $_POST['guess']." is too small! Try a larger number.";
$Som = 'Guess the number: ' . $_SESSION['num1'] .'*' .$_SESSION['num2'];
}
// some other condition
else {
$message = "I am terribly confused.";
}
}
?>
<html>
<body>
<h2><?php echo $Som . '<br>'; ?>
<?php echo $message; ?></h2>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="guess"><br>
<input type="submit" value="Check">
</form>
</body>
</html>
I'm making a simple guestbook script in php. I pretty much have it finished but need help finding the logic errors in my code. One is that when echoing the results from the form content. I am wanting to display the email, whole name and comment, each on different lines.
like this
email: some#email.com
Name: joe somebody
Comment:
hello world.
but for some reason it just displays the first and last name on all lines.
the other 3 issues are sorting(ascending, descending) and removing duplicates.
Thanks in advance for your advice on how to fix this.
I just ask you be detailed so i know what you are talking about.
In any case, heres the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Guest Book</title>
</head>
<body>
<?php
// is there data in the fields
if (isset($_POST['submit'])){
$firstName = addslashes($_POST['first_name']);
$lastName = addslashes($_POST['last_name']);
$wholeName = $firstName . "," . $lastName;
$email = addslashes($_POST['email']);
$comment = addslashes($_POST['comment']);
$guestRecord = "$wholeName~$email~$comment\n";
$guestBook = fopen("guestbook.txt", "ab");
//if not let the user know
if ($guestBook === FALSE)
echo "There was an error saving your entry!\n";
else {
// if there is info add it to the txt file
fwrite($guestBook, $guestRecord);
// close the txt file
fclose($guestBook);
//let the user know info was saved
echo "Your entry has been saved.\n";
}
}
?>
<h2>Enter your name to sign our guest book</h2>
<hr>
<form method="POST" action ="GuestBook1.php">
<p>First Name<input type ="text" name="first_name"/></p>
<p>Last Name<input type ="text" name="last_name"/></p>
<p>Email<input type ="text" name="email"/></p>
<p><textarea name="comment" id="comment"/></textarea></p>
<p><input type ="submit" value ="Submit" name="submit"/></p>
</form>
<hr>
<p>Show Guest Book
<br />
Delete Guest Entry
<br />
Remove Duplicate Entries
<br />
Sort Entries A-Z
<br />
Sort Entries Z-A
<br />
</p>
<?php
// if theres info in the form process info
if (isset($_GET['submit'])) {
if ((file_exists("guestbook.txt")) &&
(filesize("guestbook.txt") != 0)) {
$guestArray = file("guestbook.txt");
//switch to $_Get Method
switch ($_GET['submit']) {
// remove duplicate entries
case 'Remove Duplicates':
$guestArray = array_unique($guestRecord);
$guestArray = array_values($guestRecord);
break;
//sort ascending
case 'Sort Ascending':
$guestArray = sort($guestArray);
break;
//sort Decending
case 'Sort Decending':
$guestArray = ksort($guestArray);
break;
}
//count to see how many entries there are
if (count($guestArray)>0) {
$newGuest = implode($guestArray);
$guestStore = fopen("guestbook.txt", "ab");
if ($guestStore === false)
echo "There was an error updating the message file\n";
else {fwrite($guestStore, $newGuest);
fclose($guestStore);
}
}
else
unlink("guestbook.txt");}
}
if ((!file_exists("guestbook.txt")) ||
(filesize("guestbook.txt") == 0))
echo "<p>There are no entries.</p>\n";
else {
// there isnt anything in the txt file show an error
if ((!file_exists("guestbook.txt")) ||
(filesize("guestbook.txt") == 0))
echo "<p>There are no entries.</p>\n"; else {
//if there is information display the txt file in a table
$guestArray = file("guestbook.txt");
echo "<table style=\"background-color:lightgray\"
border=\"1\" width=\"100%\">\n";
//begin counting number of guest entries
$count = count($guestArray);
for ($i = 0; $i < $count; ++$i) {
$currMsg = explode("~", $guestArray[$i]);
// display results in a table
echo "<td width=\"5%\" style=\"text-align:center;
font-weight:bold\">" . ($i + 1) . "</td>\n";
echo "<td width=\"95%\"><span style=\"font-weight:bold\">
Email:</span> " . htmlentities($currMsg[0]) . "<br />\n";
echo "<span style=\"font-weight:bold\">Name:</span> " .
htmlentities($currMsg[0]) . "<br />\n";
echo "<span style=\"text-decoration:underline;
font-weight:bold\">Comment</span><br />\n" .
htmlentities($currMsg[0]) .
"</td>\n";
echo "</tr>\n";
}
echo "</table>\n";
}
}
?>
</body>
</html>
$firstName = addslashes($_POST['first_name'])."\r\n";
The \r\n\ will put things physically on a new line. Make sure to use double quotes.
Regarding your first issue, you are echoing $currMsg[0] for all of the fields. You need to use the correct index for each of the values (0 for name, 1 for email, 2 for comment). Or even better, use something like:
list($name, $email, $comment) = explode("~", $guestArray[$i]);
That way you have meaningful variable names.
The other issues you'll need to be more specific as to what you're trying to do (and in what way your current code isn't working).
I can see at least one issue though - your links have ?action= but your switch statement is looking at $_GET['submit'], not $_GET['action']. Plus you have a typo in case 'Sort Decending': (missing 's')
Here is the code i made, im expecting it to work but somewhere there must be an error. I can't figure out myself, Please help.
<?php
if(isset($_POST['submit'])){
$max_size = 500000;
$image_upload_path = "images/products/";
$allowed_image_extension = array('jpg','jpeg','png','gif');
for($i=0;$i<2;$i++)
{
//check if there is file
if((!empty($_FILES['image[]'][$i])) && ($_FILES['image[]']['error'][$i]==0))
{
//check extension
$extension = strrchr($_FILES['image']['name'][$i], '.');
if(in_array($extension,$allowed_image_extension))
{
//check file size.
if($_FILES['image']['size'][$i] > $max_size)
{
echo "file too big";
}
else if($_FILES['image']['size'][$i] < 1)
{
echo "file empty";
}
else
{
//we have pass file empty check,file extension check,file size check.
$the_uploaded_image = $_FILES['image']['tmp_name'][$i];
$the_uploaded_image_name = $_FILES['image']['name'][$i];
//replace empty space in filename with an underscore '_'
$the_uploaded_image_name = preg_replace('/\s/','_',$the_uploaded_image_name);
//get the file extension
$the_uploaded_image_extension = explode(',',$the_uploaded_image_name);
$the_new_image_name = $the_uploaded_image_name."".md5(uniqid(rand(),true))."".$the_uploaded_image_extension;
$save_image_as = $the_new_image_name;
//check file exist
if(file_exists($image_upload_path."".$the_new_image_name))
{
echo "file".$image_upload_path."".$the_new_image_name." already exist";
}
else
{
if(move_uploaded_file($the_uploaded_image,$save_image_as))
{
echo "image".$the_uploaded_image_name." uploaded sucessfully";
//set the image path to save in database column
}
else
{
echo "there was an error uploading your image.";
}
}
}
}
else
{
echo "extension not allowed";
}
}
else
{
echo "please choose file to upload";
}
}
}
?>
<html>
<head><title>image upload</title></head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image[]"/>
<input type="file" name="image[]"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
This is my new PHP code . Im getting both the result as found found not found not found. Will someone tell me what am i doing wrong here. The if else condition is seems to be not working as both the conditions are giving ouput. Why?
<?php
if(isset($_POST["submit"])) {
echo $_POST["submit"];
echo "<br/>";
for($i=0;$i<count($_FILES['image'])-1;$i++)
{
if(!empty($_FILES['image']['tmp_name'][$i]))
{
echo "found";
echo "<br/>";
}
else
{
echo "not found";
echo "<br/>";
}
}
}
else
{
echo "form is not posted";
}
?>
I guess the obvious WTF would be $_FILES['image[]'][$i], which should just be $_FILES['image'][$i] (the [] in the name makes it an array, it's not part of the name).
I'm unwilling to troubleshoot anything beyond this for you without more information. Try this at various points in the code:
echo '<pre>';
var_dump($_POST); // or other variables
echo '</pre>';
This should help you to debug your own code, something you must learn to do.