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.
Related
I am trying to upload multiples files using PHP and HTML but even I set the validation in my code isset, the foreach loop runs once with empty submission.
<?php
if (isset($_FILES['fileToUpload']))
{
foreach($_FILES['fileToUpload']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key . $_FILES['fileToUpload']['name'][$key];
$file_size = $_FILES['fileToUpload']['size'][$key];
$file_tmp = $_FILES['fileToUpload']['tmp_name'][$key];
$file_type = $_FILES['fileToUpload']['type'][$key];
move_uploaded_file($file_tmp, getcwd() . "/" . time() . $file_name);
}
echo "Success";
}
else
{
echo "<form enctype='multipart/form-data' action='' method='POST'>";
echo "File:<input name='fileToUpload[]' multiple='multiple' type='file'/><input type='submit' value='Upload'/>";
echo "</form>";
}
?>
You have to check the file name whether it is empty or not before run the foreach loop using PHP
<?php
if (isset($_FILES['fileToUpload']))
{
if($_FILES['fileToUpload']['tmp_name'][0] == "") {
die("No files to upload");
}
else {
// Now there are some files you can run upload method here
foreach($_FILES['fileToUpload']['tmp_name'] as $key => $tmp_name) {}
}
}
?>
You can check errors for UPLOAD_ERR_NO_FILE or just check for general errors (as below).
<?php
if($_FILES['userfile']['error'] == 0) {
// do something
} else {
// handle
}
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 ;
In my script on line 67 the echo statement "Your Song has been added to the list" displays before I add any songs to the list. Can anyone tell me why? It is under the comment step 8 and step 9. I have xdebug set up with sublime text 3 but I have no clue on how to use it. When I set breakpoints and run the script I get a bunch of uninitialized variables in my Context pane.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Song Organizer</title>
</head>
<body>
<h1>Song Organizer</h1>
<?php
if (isset($_GET['action'])) {
if ((file_exists("SongOrganizer/songs.txt")) && (filesize("SongOrganizer/songs.txt") != 0)) {
$SongArray = file("SongOrganizer/songs.txt");
switch ($_GET['action']) {
case 'Remove Duplicates':
$SongArray = array_unique($SongArray);
$SongArray = array_values($SongArray);
break;
case 'Sort Ascending':
sort($SongArray);
break;
case 'Shuffle':
shuffle($SongArray);
break;
} // End of the Switch Statement
if (count($SongArray)>0) {
$NewSongs = implode($SongArray);
$SongStore = fopen("SongOrganizer/songs.txt", "wb");
if ($SongStore === false)
echo "There was an error updating the song file\n";
else {
fwrite($SongStore, $NewSongs);
fclose($SongStore);
}
}
else
unlink("SongOrganizer/songs.txt");
}
}
// Step 7
if (isset($_POST['submit'])) {
$SongToAdd = stripslashes($_POST['SongName']) . "\n";
$ExistingSongs = array();
if (file_exists("SongOrganizer/songs.txt") && filesize("SongOrganizer/songs.txt") > 0) {
$ExistingSongs = file("SongOrganizer/songs.txt");
}
}
// Step 8 and Step 9
if (in_array($SongToAdd, $ExistingSongs)) {
echo "<p>The song you entered already exists!<br />\n";
echo "Your song was not added to the list.</p>";
} else {
$SongFile = fopen("SongOrganizer/songs.txt", "ab");
if ($SongFile === false)
echo "There was an error saving your message!\n";
else {
fwrite($SongFile, $SongToAdd);
fclose($SongFile);
echo "Your Song has been added to the list.\n";
}
}
// Step 10
if ((!file_exists("SongOrganizer/songs.txt")) || (filesize("SongOrganizer/songs.txt") == 0))
echo "<p>There are no songs in the list.</p>\n";
else {
$SongArray = file("SongOrganizer/songs.txt");
echo "<table border=\"1\" width=\"100%\" style=\"background-color:lightgray\">\n";
foreach ($SongArray as $Song) {
echo "<tr>\n";
echo "<td>" . htmlentities($Song) . "</td>";
echo "</tr>\n";
}
echo "</table>\n";
}
?>
<p>
Sort Song List<br />
Remove Duplicate Songs<br />
Randomize Song List<br />
</p>
<form action="SongOrganizer.php" method="post">
<p>Add a New Song</p>
<p>Song Name: <input type="text" name="SongName" /></p>
<p><input type="submit" name="submit" value="Add Song to List" /><input type="reset" name="reset" value="Reset Song Name" /></p>
</form>
</body>
</html>
I believe the answer my problem was that step 8 and step 9 should have been a nested if statement inside of step 7. like so:
// Step 7
if (isset($_POST['submit'])) {
$SongToAdd = stripslashes($_POST['SongName']) . "\n";
$ExistingSongs = array();
if (file_exists("SongOrganizer/songs.txt") && filesize("SongOrganizer/songs.txt") > 0) {
$ExistingSongs = file("SongOrganizer/songs.txt");
// Step 8 and Step 9
if (in_array($SongToAdd, $ExistingSongs)) {
echo "<p>The song you entered already exists!<br />\n";
echo "Your song was not added to the list.</p>";
} else {
$SongFile = fopen("SongOrganizer/songs.txt", "ab");
if ($SongFile === false)
echo "There was an error saving your message!\n";
else {
fwrite($SongFile, $SongToAdd);
fclose($SongFile);
echo "Your Song has been added to the list.\n";
}
}
}
}
<html>
<input type='text' name='mobile phone' value='
<?php if (strpos($phone_number, '07') === 0) {
echo $phone_number;
} else {
echo $alt_phone;
}?>'
</html>
Works fine. I would like to combine the above with:
<?php if (!empty($alt_phone)) {
echo $alt_phone;
} else {
echo '07777777777';
}?>'`
I have tried ELSEIF with the new condition, and a completely separate <?php ?> section and both times I get a blank page, instead of a textbox with a telephone number in it.
I am trying to achieve this: If $phone_number is a mobile, enter this number, otherwise enter the alt_phone, unless $alt_phone is blank, then enter '07777777777'.
try
<?php
if (!empty($phone_number)) {
echo $phone_number;
}
elseif(!empty($alt_phone))
{
echo $alt_phone;
}
else{
echo '07777777777';
}
?>'`
This will do the trick
<?php
if (strpos($phone_number, '07') === 0) {
echo $phone_number;
}
else if (!empty($alt_phone)) {
echo $alt_phone;
}
else {
echo '07777777777';
}
?>
Basically I want to add one last piece of validation, if nothing is selected on the items page then an error appears or the user is returned to another page.
When submit is selected the form action sends it to the confirm page and the below is executed which displays the items selected if there is 1 or more entered if ($partno == $varname & $qty > 0) but I dont no what to put in the else part to return an error or take the user back to the previous page.
<?php
$visitor = $_POST['visitor'];
echo "<p>" . 'Hello ' . "<b>" . $visitor . "</b> " . 'please confirm your purchase(s) below.' . "</p>";
if (!($data = file('items.txt'))) {
echo 'ERROR: Failed to open file! </body></html>';
exit;
}
$total = 0;
foreach ($_POST as $varname => $varvalue) {
$qty = $varvalue;
foreach ($data as $thedata) {
list($partno, $name, $description, $price, $image) = explode('|', $thedata);
if ($partno == $varname & $qty > 0) {
echo "<tr><td><img src='$image' width='50' height='50' alt='image'</td>
<td>$partno<input type='hidden' name='$partno' value=$partno></td><td>$name</td><td>£$price</td>
<td> $qty</td><td><input type='hidden' name='visitor' value=$visitor></td>
<td><input type='hidden' name='qty' value=$qty></td></tr>";
$total = $total + $price * $qty;
} else {
}
}
}
?>
You'd have something like this:
$errors = array();
foreach(...) {
if ($partno == $varname & $qty > 0) {
... code for "ok" stuff
} else {
$errors[] = "$partno is incorrect";
}
}
if (count($errors) > 0) {
die("Errors: " . implode($errors));
}
... proceed to "success" code ...
Basically, for every test that fails, you record a message. Once the loop exits, if there's any error messages, you display them and abort processing. If there's no errors, you proceed onwards with the rest of the code.
Why not use a try catch block?
try {
if (isset($_POST)) {
if (!$email) {
throw new Exception('email is not valid', 100);
}
// everything is good process the request
}
throw new Exception('Error!', 200);
} catch (Exception $e) {
if ($e->getCode == 200) {
// redirect
} else {
// do something else
}
}
throw an Exception in your If statement, then put your data in try/catch block, so it will catch an exception if error occured
Consider the following approach: both the form and the php code to do something with the form data are on the same page. If the form was posted, you'll first check if the form was ok, after that you'll do something with the submitted data. If the form was not valid, display an error message.
The advantage is: no die() in the middle of your code, no strange redirects, everything in one script.
// simplified code in example.php
<?php
// in this variable we'll save success/error messages to print it
$msg = "";
// run this php code if the form was submitted
if(isset($_POST['submit'])) {
// is the form valid?
if (strlen($_POST['username']) == 0) {
$msg = "Please enter a username";
}
else {
// all validation tests are passed, give the user a nice feedback
// do something with the data, e.g. save it to the db
$msg = "Your data was saved. Have a great day";
}
}
?>
<div class="msg"><?php print $msg; ?></div>
<form method="post">
<input type="text" name="username">
<input type="submit" name="submit" value="Submit">
</form>