Combobox in html and php - php

If the combobox select the Archers the browser will echo Correct but if the combobox will not select the Archers the browser will echo, i want to know if my syntax is wrong.
Wrong. Error: Undefined index text_hname.
Here's the structure:
<form action="server.php" method="POST">
<img src="images/logo.png" class="logo">
<div class="container">
<h1>Account Details</h1>
<br>
<label class="username">Username</label>
<input type="text" name="text_username" class="text_user" placeholder="Enter username">
<label class="password">Password</label>
<input type="text" name="text_password" class="text_pass" placeholder="Enter password">
<label class="email">Email</label>
<input type="text" name="text_email" class="text_email" placeholder="Enter email">
<label class="cname">Character Name</label>
<input type="text" name="text_cname" class="text_cname" placeholder="Enter Character Name">
<label class="character">Select Character</label>
<select class="names" name="text_hname">
<option>Archer</option>
<option>Barbarian</option>
<option>Balloon</option>
<option>Witch</option>
<option>Spirit</option>
<option>Hog Rider</option>
<option>Minion</option>
</select>
<img src="images/">
<br>
<input type="submit" class="submit" name="submit">
</div>
</form>
//option
$hero = $_POST['text_hname'];
if (isset($_POST['text_hname'])) {
if ($hero == 'Archers') {
echo "Correct";
} else {
echo "wrong";
}
}

The problem is that if you're trying to assign $hero before you've checked if text_hname is set, it might not be defined.
Suggested refactor:
if (isset($_POST['text_hname'])) {
$hero = $_POST['text_hname'];
if ($hero == 'Archers') {
echo "Correct";
}
else
{
echo "wrong";
}
}

//Your select in form needs values. Same values that you are going to compare.
<select class="names" name="text_hname">
<option value="Archer">Archer</option>
<option value="Barbarian">Barbarian</option>
<option value="Balloon">Balloon</option>
<option value="Witch">Witch</option>
<option value="Spirit">Spirit</option>
<option value="HogRider">Hog Rider</option>
<option value="Minion">Minion</option>
</select>
//Php code
if (isset($_POST['text_hname'])) {
$hero = $_POST['text_hname'];
if ($hero == 'Archer') { //Its Archer, not Archers
echo "Correct";
}
else
{
echo "wrong";
}
}

$_POST['text_hname'] will return the selected option value , not option name .
Modify your select like this:
<select class="names" name="text_hname">
<option value="Archer">Archer</option>
<option value="Barbarian">Barbarian</option>
<option value="Balloon">Balloon</option>
<option value="Witch">Witch</option>
<option value="Spirit">Spirit</option>
<option value="Hog_Rider">Hog Rider</option>
<option value="Minion">Minion</option>
</select>
and server.php page
if (isset($_POST['text_hname'])) {
$hero = trim($_POST['text_hname']); //** to remove any whitespace
if ($hero == 'Archer') {
echo "Correct";
} else {
echo "wrong";
}
}
EDIT : it might be because your $_POST['text_hname'] has whitespace. Try trim() on $_POST['text_hname']
Hope it's helpful.

Related

Set_value() Array fields select option Codeigniter not working

I trying to create dynamic server side select input, after i submit, the set_value('nilai[]') not showing any value.
Here's my Controller below:
$this->load->library('form_validation');
$this->form_validation->set_rules('nilai[]', 'Nilai Pantuhir', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('pantuhir/pantuhir_form');
} else {
$list_pantuhir = $this->input->post('nilai');
foreach ($list_pantuhir as $key => $value) {
echo $value."<br />";
}
}
Here's my view below :
<div class="form-group <?php if(form_error('nilai[]')){echo 'has-error';} ?>">
<select class="form-control" name="nilai[]">
<option value="">- Choose-</option>
<option value="<?php echo $rowPerson['intUserId'].'-'.'A';?>" <?php if(set_value('nilai[]') == $rowPerson['intUserId'].'-'.'A') { echo 'selected'; } ?>>A</option>
<option value="<?php echo $rowPerson['intUserId'].'-'.'B';?>" <?php if(set_value('nilai[]') == $rowPerson['intUserId'].'-'.'B') { echo 'selected'; } ?>>B</option>
</select>
<?php echo form_error('nilai[]'); ?>
</div>
I want to show set_value and get selected in option field if validation not correct.
Hope this will help you :
Use set_select instead of set_value. If you use a menu, this function permits you to display the menu item that was selected, after the form validation throws any error
It should be like this :
<div class="form-group <?php if(form_error('nilai[]')){echo 'has-error';} ?>">
<select name="nilai[]" >
<option value="" >---Choose----</option>
<option
value="<?=$rowPerson['intUserId'].'-A';?>"
<?=set_select('nilai[]', $rowPerson['intUserId'].'-A');?>
>A</option>
<option
value="<?php echo $rowPerson['intUserId'].'-B';?>"
<?=set_select('nilai[]', $rowPerson['intUserId'].'-B');?>
>B</option>
</select>
<?php echo form_error('nilai[]'); ?>
</div>
For more : https://www.codeigniter.com/user_guide/helpers/form_helper.html#set_select
Use this code in the view
<div class="form-group <?php if(form_error('nilai[]')){echo 'has-error';} ?>">
<select class="form-control" name="nilai[]">
<option value="">- Choose-</option>
<option value="<?php echo $rowPerson['intUserId'].'-'.'A';?>" <?php if(set_value('nilai[]',rowPerson['intUserId'].'-'.'A') == $rowPerson['intUserId'].'-'.'A') { echo 'selected'; } ?>>A</option>
<option value="<?php echo $rowPerson['intUserId'].'-'.'B';?>" <?php if(set_value('nilai[]',$rowPerson['intUserId'].'-'.'B') == $rowPerson['intUserId'].'-'.'B') { echo 'selected'; } ?>>B</option>
</select>
<?php echo form_error('nilai[]'); ?>
</div>

issue with displaying proper output in PHP

I trying to make search option based on a SELECT box and user input (both are mandatory). But in the following code both correct and wrong input are displaying as wrong input. Can someone please explain what is wrong in the code.
Here is HTML
<form action="" method="POST">
<select name="selectOpt">
<option>Select a list</option>
<option value="one">ID</option>
<option value="delName">Dealer Name</option>
<option value="medName">Medical Name</option>
</select>
<input type="text" name="uinput" placeholder="Enter Search Key"/>
<button type="submit" name="submit">search</button>
</form>
PHP
if(isset($_POST['submit'])){
if(!empty($_POST['selectOpt']) && !empty($_POST['uinput'])){
if($_POST['selectOpt']=='one'){
$id = $_POST['selectOpt'];
if (!preg_match("/^[0-9]*$/",$id)){
echo "not valid";
}else{
echo "valid";
}
}
}else{
echo "Enter Value";
}
}
Your pattern /^[0-9]*$/, which is written to require a sequence of zero or more digits, doesn't match any of the possible values for your select box, which are all alphabetic strings.
<form action="save.php" method="POST">
<select name="selectOpt">
<option>Select a list</option>
<option value="one">ID</option>
<option value="delName">Dealer Name</option>
<option value="medName">Medical Name</option>
</select>
<input type="text" name="uinput" placeholder="Enter Search Key"/>
<button type="submit" name="submit">search</button>
</form>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['selectOpt']) && !empty($_POST['uinput'])){
if($_POST['selectOpt'] == "one"){
$id = $_POST['selectOpt'];
if (preg_match("/^[0-9]*$/",$id)){
echo "not valid";
}else{
echo "valid";
echo $input = $_POST['uinput'];
}
}
else{
echo "PLEASE Enter Proper and Valid Search ";
}
}
else{
echo "PLEASE Enter Value ";
}
}
?>

Getting empty $_FILES array

I want to upload a file to server.I have added all the code to upload file to server but the $_FILES array is empty. File Value is not getting set in an array.
I have done same code for another web page and it works fine, but not getting whats the issue in this.
I have set the enctype as multipart/form-data but still its giving empty array.
html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Post</title>
</head>
<body>
<script>
</script>
<form class="postForm" id="postForm" method="post" action="addPost.php" enctype="multipart/form-data">
<fieldset>
<legend>Please add the details below </legend>
<p>
<label for="title">Title (required, at least 2 characters)</label>
<input id="title" name="title" minlength="2" type="text" required>
</p>
<p>
<label for="desc">Description (required, at least 2 characters)</label>
<input id="desc" name="desc" minlength="2" type="text" required>
</p>
<p>
<label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
<input id="keywords" name="keywords" minlength="2" type="text" required>
</p>
<select id="types" name="types" onchange="myFunction(this)">
<option value="">Select type</option>
<option value="2">Add Link</option>
<option value="0">Upload Image</option>
<option value="1">Upload Video</option>
</select><br><br>
<div id="link" style="display: none">
<p>
<label for="url">URL (required)</label>
<input id="url" type="url" name="url" required>
</p>
<p>
<label for="urlType">Select Url Type :(required)</label>
<select name="urlType" id="urlType">
<option value="">Select Url Type...</option>
<!-- <option value="0">Server Image</option>
<option value="1">Server Video</option>-->
<option value="2">YouTube Video</option>
<option value="3">Vimeo Video</option>
<option value="4">Facebook Image</option>
<option value="5">Facebook Video</option>
<option value="6">Instagram Image</option>
<option value="7">Instagram Video</option>
<option value="-1">Other</option>
</select>
</p>
</div>
<div id="filediv" style="display: none">
Select file to upload:
<br><br>
<input name = "file" type="file" id="fileToUpload"><br><br>
</div>
<p>
<label for="postType"> Select Post Type :(required)</label>
<select name="postType" id="postType">
<option value="">Select Post Type...</option>
<option value="0">Normal</option>
<option value="1">Featured</option>
<option value="2">Sponsored</option>
</select>
</p>
<p>
<label for="category"> Select Category :(required)</label>
<select name="category" id="category">
<option value="">Select Category...</option>
</select>
</p>
<p>
<input type="hidden" name="action_type" id="action_type_id"/>
<input type="hidden" name="id" id="p_id"/>
<!-- Cancel
Add User-->
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</fieldset>
<div class="result" id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script>
function myFunction(obj) {
var type = obj.value;
var x = document.getElementById('link');
var y = document.getElementById('filediv');
if(type == "2")
{
x.style.display = 'block';
y.style.display = 'none';
}
else {
x.style.display = 'none';
y.style.display = 'block';
}
}
</script>
</form>
</body>
</html>
addPost.php
<?php
include 'Database.php';
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
if(isset($_POST['action_type']) && !empty($_POST['action_type'])) {
if($_POST['action_type'] == 'add') {
$database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
$dbConnection = $database->getDB();
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbConnection->prepare("insert into keywords(keyword)
values(?)");
$stmt->execute(array($_POST['keywords']));
$file_result = "";
if(strcmp($_POST['types'],"2") == 0)
{
//insert data into posts table
$stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type)
values(?,?,?,?,?,?,?)");
$stmt->execute(array($_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords'],$_POST['postType']));
$count = $stmt->rowCount();
if ($count > 0) {
echo "Post submitted.";
} else {
echo "Could not submit post.";
}
}
else {
if(isset($_POST['submit'])){
print_r($_FILES);
if (isset($_FILES["file"]["name"])) {
$file_result = "";
if ($_FILES["file"]["error"] > 0) {
$file_result .= "No file uploaded or invalid file.";
$file_result .= "Error code : " . $_FILES["file"]["error"] . "<br>";
} else {
if (strcmp($_POST['types'], "0") == 0) {
$target_dir = "AgTv/images/";
} else {
$target_dir = "AgTv/videos/";
}
$newfilename = preg_replace('/\s+/', '',
$_FILES["file"]["name"]);
$target_file = $target_dir . basename($newfilename);
/*$target_file = $target_dir . basename($_FILES["file"]["name"]);*/
$file_result .=
"Upload " . $_FILES["file"]["name"] . "<br>" .
"type " . $_FILES["file"]["type"] . "<br>" .
"temp file " . $_FILES["file"]["tmp_name"] . "<br>";
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
$stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type)
values(?,?,?,?,?,?,?)");
$stmt->execute(array($_POST['category'], $_POST['title'], $newfilename, $_POST['types'], $_POST['desc'], $_POST['keywords'], $_POST['postType']));
$count = $stmt->rowCount();
if ($count > 0) {
echo "The file " . basename($_FILES['file']['name']) . " has been uploaded, and your information has been added to the directory";
} else {
echo "Could not submit post.";
}
}
}
}
else{
echo 'empty file';
}
}
}
}
}
?>
Can anyone help please? Thank you.
UPDATED WITH SOLUTION:
just add
<script>
$("#postForm").validate();
</script>
below the inclusion of jquery.validate.min.js. You $_FILES array is working fine, you are just not sending the post at all!

Don't Know How to Add Existing Image Upload Capabilities to a New Form

I'm a fairly novice webmaster whom is working hard to setup a classifieds for my users. (I'm basically rebuilding a poorly written classifieds)
I had bought a cheap classifieds program so I'd have something to learn PHP off of and I've come a long ways but I'm still a long ways off from understanding how to tie everything together with an existing image upload functionality and if anyone wouldn't mind helping me, I'd be most appreciative.
Allow me to explain;
In this classifieds earliest days, a visitor had to add their listing (which was a bitch) THEN the visitor had to go looking for where they could upload their images. Needless to say, that wasn't cutting it.
Fast Fwd to Present; Now I have a form on a page with several text inputs (ie; text, select, textarea and a checkbox) as well as on this form I have 4 image upload buttons as can be seen below.
<form id="generalform" class="container" method="POST" action="addlistingprocess.php" autocomplete="on" enctype="multipart/form-data" >
<div class='field'>
<label for='TypeID'>I'm Selling A:</label>
<select name='TypeID'>
<option value='42'>Motorcycle</option>
<option value='43'>New or Used Part</option>
</select>
</div>
<div class="field">
<label for="Year">* Year:</label>
<input type="number" class="input" name="Year" maxlength="5" min="1963" max="2013" value="2013">
</div>
<div class="field">
<label for="fatherID">* Make:</label>
<select name='fatherID'>
<option>-- Select Manufacturer --</option>
<option value='10'>Honda</option>
<option value='35'>Husqvarna</option>
<option value='36'>Kawasaki</option>
<option value='37'>KTM</option>
<option value='38'>Suzuki</option>
<option value='39'>Yamaha</option>
<option value='40'>Other</option>
<option value='46'>It's Vintage or Evo</option>
</select>
</div>
<div class="field">
<label for="Model">* Model:</label>
<input type="text" class="input" name="Model" maxlength="20" value="<?php if(isset($_POST['Model'])) echo $_POST['Model']; ?>" placeholder="(i.e. CRF450F, KX 450F...)">
</div>
<div class="field">
<label for="Description">* Details About It:</label><br>
<textarea name="Description" rows="10" cols="60"><?php if(isset($_POST['Description'])) echo $_POST['Description']; ?></textarea>
</div>
<div class="field">
<label for="Vin">VIN:</label>
<input type="text" class="input" name="VIN" maxlength="30" value="<?php if(isset($_POST['VIN'])) echo $_POST['VIN']; ?>" placeholder="Optional">
</div>
<div class="field">
<label for="Price">* Asking Price ($):</label>
<input type="number" class="input" name="Price" maxlength="10" min="0" value="<?php if(isset($_POST['Price'])) echo $_POST['Price']; ?>">
</div>
<!--
<h4>Upload Up To 4 Images</h4>
<div class="field">
<label for="Image">Image 1</label>
<input type="file" class="fileuploadinput" name="Image1">
<label for="Image">Image 2</label>
<input type="file" class="fileuploadinput" name="Image2">
<label for="Image">Image 3</label>
<input type="file" class="fileuploadinput" name="Image3">
<label for="Image">Image 4</label>
<input type="file" class="fileuploadinput" name="Image4">
</div>
-->
<br>
<hr style="width:60%">
<br>
<h3>Where It's Located:</h3>
<div class="field">
<label for="Address">Address:</label>
<input type="text" class="input" id="Address" name="Address" maxlength="40" placeholder="Optional" />
<p class="hint">40 Characters Maximum</p>
</div>
<div class="field">
<label for="City">* City:</label>
<input type="text" class="input" id="City" name="City" maxlength="20" />
<p class="hint">20 Characters Maximum</p>
</div>
<div class="field">
<label for="State">* State / Province:</label>
<input type="text" class="input" id="State" name="State" maxlength="20" />
<p class="hint">20 Characters Maximum</p>
</div>
<div class="field">
<label for="ZIP">* ZIP:</label>
<input type="text" class="input" id="ZIP" name="ZIP" maxlength="20" />
<p class="hint">20 Characters Maximum</p>
</div>
<div class="field">
<label for="Country">* Country:</label>
<select name="Country">
<option selected="selected" value="United States">United States</option>
<option value="Canada">Canada</option>
<option value="UK">UK</option>
<option value="Zimbabwe">Zimbabwe</option>
</select>
</div>
<input type="checkbox" name="Inform" value="1" checked/> Keep Me Dialed In With Site Updates & Specials<br><br>
<input type="submit" name="submit" id="submit" class="button" value="Submit My Ad"/>
</form>
Now here's the kicker, (and sorry for creating such a long post)
This classifieds already has an existing image upload functionality which I'd like to retain as it handles resizing and displaying the images such as can be seen here:
http://classifieds.your-adrenaline-fix.com/detail.php?fatherID=10&TypeID=42&ListingID=7
I want to tie this functionality to the form above, however, this program requires a lot of paramaters of which I have tried for weeks to understand, yet still don't. (However I have cleaned the sh^$ out of the code in an effort to understand it)
I'm going to close this thread with all applicable files as code and if anyone could help me with this I'd be most grateful and I thank you all in advance.
This is images.php. (This is where a visitor had to navigate to AFTER creating their ad but it's also where a visitor can add or delete photos associated with their listing so I need to keep this)
<?php
include('header.php');
if(!$superUser){
if(!$login){
echo "<h2>Please Login to Manage Photos</h2>";
include('z-login-form.php');
include('no-ad-footer.php');
die();
}
}
if($_POST['POrder'] != "") {
if (($_FILES['file']['type'] != 'image/jpeg') && ($_FILES['file']['type'] != 'image/jpg') && ($_FILES['file']['type'] != 'image/pjpeg')) {
echo "<script>alert('Images Must be in jpg format and under 2 Mb');\n";
echo sprintf("window.location='images.php?TypeID=%s&ListingID=%s'", $_POST['TypeID'], $_POST['ListingID']);
echo "</script>";
include('no-ad-footer.php');
die();
}
chdir('admin/photos');
require_once('upload.php');
chdir('../../');
if ($up->ValidateUpload()) {
$node = new sqlNode();
$node->table = "photos";
$node->push("int","POrder",$_POST['POrder']);
$node->push("text","Location",$new_name);
$node->push("int","TypeID",$_POST['TypeID']);
$node->push("int","ListingID",$_POST['ListingID']);
if(($result = $mysql->insert($node)) === false)
die('Unable to push POrder, Location, TypeID and ListingID into table photos line 38');
} else {
echo "<font color='red'>Unable to upload image</font>";
}
}
if(($_REQUEST['TypeID'] != "") && ($_REQUEST['ListingID'] != "")) {
if(!$superUser){
echo "<a href='memberindex.php'>Return to My Listings</a>";
}
$sql = sprintf("SELECT * FROM `types` WHERE ID = %s", intval($_REQUEST['TypeID']));
$result = $mysql->exSql($sql) or die('Unable to Retrieve Type ID from table types');
if(mysql_num_rows($result)<1){
die('Less Than One Result Returned from table types. Line51 images.php');
}
if(!$superUser){
$sql = sprintf("SELECT * FROM `tt_%s` WHERE MemberID = %s AND ID = %s", abs(intval($_REQUEST['TypeID'])), intval($_SESSION['memberID']), intval($_REQUEST['ListingID']));
$result = $mysql->exSql($sql) or die('Unable to select data from table tt__');
if(mysql_num_rows($result)<1){
die("<script>window.location='logout.php';</script>");
}
}
$node = new sqlNode();
$node->table = "photos";
$node->select = "*";
$node->where = "WHERE TypeID = ".intval($_REQUEST['TypeID'])." AND ListingID = ".intval($_REQUEST['ListingID']);
$node->orderby = "ORDER BY `POrder` ASC";
if(($result = $mysql->select($node)) === false )
die('Unable to Retrieve data from table photos');
$num_of_photos = mysql_num_rows($result);
echo "<h2>Upload or Delete Photos</h2>";
$showform = true;
if($showform) {
echo "<form action='images.php' enctype='multipart/form-data' method='POST'>";
echo "<input type='hidden' name='TypeID' value='".$_REQUEST['TypeID']."'>";
echo "<input type='hidden' name='ListingID' value='".$_REQUEST['ListingID']."'>";
echo "<input type='hidden' name='Upload' value='true'>";
echo "<input type='hidden' name='POrder' value='".($num_of_photos+1)."'>";
echo "<table border=0>";
echo "<tr>";
echo "<td>Image 1</td><td><input type='file' name='file' accept='image/*' id='file'></td>";
echo "</tr>";
echo "<tr>";
echo "<td> </td><td><input type='submit' value='Upload File(s)'></td>";
echo "</tr>";
echo "</table>";
echo "</form>";
} else {
echo "<font color='red'>Max Number of Photos Reached</font>";
}
if($num_of_photos >=1) {
//Print photo table
echo "<br>";
echo "<center><strong>$num_of_photos Photo(s) Associated With This Listing</strong></center>";
echo "<table class='subHeader' align='center'>";
echo "<tr>";
echo "<td>Photo</td><td>Order | </td><td>Action</td>";
echo "</tr>";
//For each photo
while($photo = mysql_fetch_assoc($result)){
echo "<tr>";
echo "<td valign=top align=center>";
echo "<a target='_blank' href='admin/photos/uploads/".$photo['Location']."' title='Click To View Full Size Photo'><img src='admin/photos/uploads/small_thumbs/tn_".$photo['Location']."' border=0></a>";
echo "</td>";
echo "<td>".$photo['POrder']."</td>";
echo "<td>";
echo "<a href='deleteimage.php?TypeID=".$photo['TypeID']."&ListingID=".$photo['ListingID']."&PhotoID=".$photo['ID']."'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
}
echo "</td>";
echo "</tr>";
echo "</table>";
include('no-ad-footer.php');
?>
This is upload.php
<?php
require_once("UploadFile.class.php");
$up = new UploadImage($file, 2097152, 3000, 3000,'file',"uploads", $rename_file=true);
if(true) {
$new_name = $up->CopyFile();
$imagefolder='.';
$thumbsfolder='.';
echo "Creating thumbnail image...<br>";
function createthumb($name,$filename,$new_w,$new_h) {
$system=explode(".",$name);
if (preg_match("/jpg|jpeg/",$system[1])){$src_img=imagecreatefromjpeg($name);}
if (preg_match("/png/",$system[1])){$src_img=imagecreatefrompng($name);}
$old_x=imageSX($src_img);
$old_y=imageSY($src_img);
if ($old_x > $old_y) {
$thumb_w=$new_w;
$thumb_h=$old_y*($new_h/$old_x);
}
if ($old_x < $old_y) {
$thumb_w=$old_x*($new_w/$old_y);
$thumb_h=$new_h;
}
if ($old_x == $old_y){
$thumb_w=$new_w;
$thumb_h=$new_h;
}
$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
if (preg_match("/png/",$system[1])){
imagepng($dst_img,$filename);
} else {
imagejpeg($dst_img,$filename);
}
imagedestroy($dst_img);
if(!imagedestroy($src_img)){
$return = #unlink($filename);
$return2 = #unlink($name);
// Return FALSE if not found
var_dump($return);
var_dump($return2);
?>
<script>alert("Unable to resize photos. Please check file/folder permission in admin/photos.");window.location ="index.php";</script>
<?php
}
}
createthumb("uploads/" . $new_name,"uploads/thumbs/tn_" . $new_name,350,350);
createthumb("uploads/" . $new_name,"uploads/small_thumbs/tn_" . $new_name,150,150);
function ditchtn($arr,$thumbname){
foreach ($arr as $item) {
if (!preg_match("/^".$thumbname."/",$item)){$tmparr[]=$item;}
}
return $tmparr;
}
function directory($dir,$filters){
$handle=opendir($dir);
$files=array();
if ($filters == "all"){while(($file = readdir($handle))!==false){$files[] = $file;}}
if ($filters != "all"){
$filters=explode(",",$filters);
while (($file = readdir($handle))!==false){
for ($f=0;$f<sizeof($filters);$f++):
$system=explode(".",$file);
if ($system[1] == $filters[$f]){$files[] = $file;}
endfor;
}
}
closedir($handle);
return $files;
}
}
?>
This is UpLoadFileclass.php
<?php
function RandomFile($pass_len=12) {
$allchar = "abcdefghijklmnopqrstuvwxyz" ;
$str = "" ;
mt_srand (( double) microtime() * 1000000 );
for ($i=0; $i<$pass_len; $i++)
$str .= substr( $allchar, mt_rand (0,25), 1 ) ;
return $str ;
}
class UploadImage {
var $image;
var $imagesize;
var $max_file_size;
var $max_file_height;
var $max_file_width;
var $allowed;
var $rename_file;
var $path;
function UploadImage($image, $max_file_size, $max_file_height, $max_file_width, $field_name, $path, $rename_file=true) {
$this->image=$image;
$this->max_file_size=$max_file_size;
$this->max_file_height=$max_file_height;
$this->max_file_width=$max_file_width;
$this->allowed = array( ".jpg"=>"2", ".jpeg"=>"2");
$this->field_name = $field_name;
$this->path = $path;
$this->rename_file = $rename_file;
}
function ValidateUpload() {
if ($this->max_file_size < filesize($this->image)) {
print("<span style=\"color:red;\">ERROR: Your File: ".$_FILES[$this->field_name]["name"]." is ".filesize($this->image)." KB, The max file size allowed is ".$this->max_file_size."</span>");
return false;
}
$this->imagesize=getimagesize($this->image);
if ($this->max_file_width < $this->imagesize[0]) {
print("<span style=\"color:red;\">ERROR:<br />Your File: ".$_FILES[$this->field_name]["name"]." is ".$this->imagesize[0]." pixels wide, the max file width allowed is ".$this->max_file_width."</span>");
return false;
}
if ($this->max_file_height < $this->imagesize[1]) {
print("<span style=\"color:red;\">ERROR:<br />Your File: ".$_FILES[$this->field_name]["name"]." is ".$this->imagesize[1]." pixels high, the max file height allowed is ".$this->max_file_height."<span>");
return false;
}
return true;
}
function PrintForm($max_file_size) {
global $PHP_SELF;
print("<form action=\"$PHP_SELF\" method=\"POST\" enctype=\"multipart/form-data\"></br>\n");
print("<input type=file name=$this->field_name><br>\n");
print("<input type=hidden name=max_file_size value=".$max_file_size."><br>\n");
print("<input type=submit name=submit><br>\n");
print("</form>");
}
function CopyFile() {
if($this->rename_file) {
global $name, $ext;
switch($_FILES[$this->field_name]["type"]) {
case 'image/gif';
$ext="gif";
break;
case 'image/jpeg';
$ext="jpg";
break;
case 'image/pjpeg';
$ext="jpg";
break;
case 'image/png';
$ext="png";
break;
case 'application/x-shockwave-flash';
$ext="swf";
break;
case 'image/psd';
$ext="psd";
break;
case 'image/bmp';
$ext="bmp";
break;
}
$name=RandomFile();
if(!copy($_FILES[$this->field_name]["tmp_name"],$this->path."/".$name.".".$ext)){
print("<strong>There has been an error while uploading Filename:".$_FILES[$this->field_name]["name"] ."</strong>");
} else {
print("Filename: ".$_FILES[$this->field_name]["name"] ." has been uploaded");
//return new file name
return $name.".".$ext;
}
} else {
if(!file_exists($this->path."/".$_FILES[$this->field_name]["name"])) {
if(!copy($_FILES[$this->field_name]["tmp_name"],$this->path."/". $_FILES[$this->field_name]["name"])) {
print("There has been an error uploading".$_FILES[$this->field_name]["name"]."please try again");
} else {
print("Filename:".$_FILES[$this->field_name]["name"]." has been uploaded");
}
} else {
print("ERROR: A file by this name already exists");
}
}
}
}
?>
Once again, If anyone could help me to make sense of all of this, I'd be most appreciative and I thank you all again (in advance)
have you tried adding the includes to the page your form is on?
include_once("upload.php");
include_once("UpLoadFileclass.php");

Post back the data if validation fails for "Select"

Once submitted selected option, the data is not stored.
just want to know how to post back the data if validation fails
The following line doesnt really work for me.
<select id="numbers" name="numbers" value="<?php echo (isset($_POST['numbers'])) ? $_POST['numbers'] : " "; ?>"/>
if someone could give me a hand?
Many thanks, here is my code
<?php
if(isset($_POST['numbers']) &&($_POST['fruits']) && $_POST['numbers'] != "null" && $_POST['fruits'] !== "null")
{
echo "Thank you!";
} elseif (isset($_POST['numbers']) && $_POST['numbers'] = "null") {
echo "you forgot to choose a number";
}
elseif(isset($_POST['fruits']) && $_POST['fruits'] = "null")
{
echo "you forgot to choose fruit name";
}
?>
<form id="form" name="form" method="post" action="">
<label for="expiry">Select</label>
<select id="numbers" name="numbers" value="<?php echo (isset($_POST['numbers'])) ? $_POST['numbers'] : " "; ?>"/>
<option value="null" selected="selected">-</option>
<option value="01">01</option>
<option value="02">02</option>
<option value="03">03</option>
</select>
<select id="fruits" name="fruits" value="<?php echo (isset($_POST['fruits']))? $_POST['fruits'] : ''; ?>"/>
<option value="null" selected="selected">-</option>
<option value="Apple">Apple</option>
<option value="Banana">Banana</option>
<option value="Pear">Pear</option>
</select>
<input type="submit" value="Send" />
</form>
Solved it, Maybe not a best way, but at least got it sorted:
<?php
$item = null; #
$itemyear = null;
if(isset($_POST['numbers'])){
$item = $_POST['numbers'];
}
if(isset($_POST['fruits'])){
$itemyear = $_POST['fruits'];
}
if(isset($item) && isset($itemyear) && $item != "null" && $itemyear !== "null")
{
echo "Thank you!";
} elseif ($item == "null") {
echo "you forgot to choose a number";
}
elseif($itemyear == "null")
{
echo "you forgot to choose fruit name";
}
?>
<form id="form" name="form" method="post" action="">
<label for="expiry">Select</label>
<select id="numbers" name="numbers" />
<option value="null" selected="selected">-</option>
<option value="01" <?php if($item == '01'): echo "selected='selected'"; endif; ?>>01</option>
<option value="02" <?php if($item == '02'): echo "selected='selected'"; endif; ?>>02</option>
<option value="03" <?php if($item == '03'): echo "selected='selected'"; endif; ?>>03</option>
</select>
<select id="fruits" name="fruits" />
<option value="null" selected="selected">-</option>
<option value="Apple"<?php if($itemyear == 'Apple'): echo "selected='selected'"; endif; ?> >Apple</option>
<option value="Banana"<?php if($itemyear == 'Banana'): echo "selected='selected'"; endif; ?>>Banana</option>
<option value="Pear"<?php if($itemyear == 'Pear'): echo "selected='selected'"; endif; ?>>Pear</option>
</select>
<input type="submit" value="Send" />
</form>
<?php
echo $item ."-". $itemyear;
?>
the PHP isset() function returns either true or false (depending on whether the input is.. well... set.
You would want to use this:
value='<?php echo (isset($_POST['numbers'])) ? $_POST['numbers'] : ""; ?>
You can't set a value attribute on a <select>. You have to find the correct <option> and set its selected attribute. Personally, I put a data-default attribute on the <select> and then use JavaScript to loop through the options and find the right one.
Oh now I see.
I don't know what the usual thing to do is but one way is to put all the data as a query string when you redirect the user back. The reason why it doesn't stay in the $_POST global is because it's only kept on the page you post to then it's gone.
So when you redirect the user back
if(validationFailed)
{
header("Location: page.php?data=example");
}
The data can then be retrieved in page.php by using
$data = $_GET['data']; // contains "example"

Categories