PHP: If value is empty, to not sumbit target filepath to database - forms

I have a very slight problem where I am not able to figure out how to get my target filepath not submit to the mysql database when the field value is empty. Right now, if I leave the image field empty, it still submits the filepath ($folder) to the database. I would like for when the field is left empty, to not send the filepath to mysql.
Form.php
<form enctype="multipart/form-data" action="add.php" method="POST">
HAZARD: <input name="haz1" value="hazard1" type="text" /><br>
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
IMAGE: <input type="file" name="photo"><br>
<input type="submit" name="action" value="Load">
</form>
Add.php
<?php
$folder = "images/";
$target1 = $folder . basename( $_FILES['photo']['name']);
$photo = $target1;
require("../db.php");
$haz1 = $_POST['haz1'];
mysql_query("INSERT INTO testimg VALUES (null,'$haz1','$photo')") ;
move_uploaded_file($_FILES['photo']['tmp_name'], $target1);
?>
I've tried
if (isset($_POST['photo']) ? $_POST['photo'] : null) echo $target1 == null);
I've tried other ways of isset as well but doesn't seem to work. Is there any other way i can accomplish this? Appreciate any help please. Thank you!
(Just a note, I have removed excess code above just to keep it short. I am taking care of SQL injection)

I would strongly suggest JavaScript, then users do not need to reload the page if it is empty. The JavaScript will check if it is empty for you. If it is you can make it so they cannot submit at all.
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
This is an example above, if you would like better walk through go here
JQuery has libraries that you can use to do fancy things if it is left blank, just search for JQuery form validation for more tools.
Hope this helps!

Try using the inbuild HTTP_POST_FILE in PHP:
if (isset($_FILES['photo']) ? $_FILES['photo'] : null)
You could wrap the mysql code inside of an if function too:
if (isset($_FILES['photo']) {
//Do mySQL processing in here
}

A couple of points:
Require is at the top of a PHP script. It's nicer to see all requires
first.
I have used an inline if statement to determine what to set $photo
(elimintating need for $target1)
I have also moved the apostrophes into the assignment of $photo as
returning 'null' comapred to null (without the quotation marks) is
very different in SQL.
If $photo is not null at the end of the script then it moves the
updated file.
Please see the corrected code below:
<?php
require("../db.php");
$folder = "images/";
$photo = (isset($_FILES['photo']) ? "'" . $folder . basename( $_FILES['photo']['name']) . "'" : null);
$haz1 = $_POST['haz1'];
mysql_query("INSERT INTO testimg VALUES (null,'$haz1',$photo)") ;
if ($photo != null) { move_uploaded_file($_FILES['photo']['tmp_name'], $photo); }
?>

Related

Secure SQL update in PHP

As part of a job I want to update a database using a form. Since the database is large and is used by many users, I hope that this manipulation is at least secure for more safety.
HTML script :
<form action="http://localhost/modifier_infos_signaletique.php" method=POST >
<div class="id_sign">
<h5>Id "Signalétique" :</h5>
<input type="text" name="id_sign" id="id_sign"/><br>
</div>
<h5>Infos "Signalétique" : </h5>
<input class="comment" type="text" id="maj_infos" name="maj_infos" required maxlength='140'/><br>
<input type="submit" value="Submit" />
</form>
PHP script:
<?php
$user = 'xxxx';
$pass = 'xxxx';
try{
$dbconn = new PDO('pgsql:host=localhost;port=5432;dbname=xxxx',$user, $pass);
$dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$maj = $_POST['maj_infos'];
$id = $_POST['id_sign'];
$query = $dbconn->prepare("UPDATE signaletique SET infos = ':infos' WHERE id = ':id'");
$query->bindParam(':infos', $maj, PDO::PARAM_STR);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
echo 'Données mises à jour';
}
catch(PDOException $e){
echo "Erreur : " . $e->getMessage();
}
?>
However, when I use this script this error appears:
**Erreur : SQLSTATE[HY093]: Invalid parameter number: :infos **
The error would be due to the parameter used for the bindParam function.
However, I have in the properties of my PostgreSQL database, info in "character varying". I tried to change this parameter to "text", but the error remains the same.
Forgive me for this question but I am new to PHP and my SQL skills are thin since I use pgAdmin and its tools a lot to build and interact with my databases.
Here is a screenshot of my database :
The info parameter is in "text" on the screenshot but basic this property was in "character varying" (140).
Thank you for your help.
In your query string you put single quotes around your placeholders. This makes them strings, not placeholders. You do not need quotes when using placeholders.
This should work:
$query = $dbconn->prepare("UPDATE signaletique SET infos = :infos WHERE id = :id");
See https://stackoverflow.com/questions/10966251/sqlstatehy093-invalid-parameter-number-parameter-was-not-defined for more information.

create folder using a form with a given name

Im trying to make a html form that can create a folder on the server with a given name in the html form. So fare I have this code:
<?
if (isset($_POST['createDir'])) {
//get value of inputfield
$dir = $_POST['dirname'. var_dump($_POST)];
//set the target path ??
$targetfilename = PATH . '/' . $dir;
if (!file_exists($dir)) {
mkdir($dir, 0777, true); //create the directory
}
}
print_r($_POST); exit;
?>
<form method="POST" action="<?=$_SERVER["PHP_SELF"]?>" name="myform" id="myform">
<input name="dirname" id="dirname" >
<input type="submit" name="dirname" value="dirname" title="Continue to the next step">
</form>
The debug say: Array ( )
the script is nothing i have wrote but trying to put thing together to get it working but have not fix this for days now. Please advice.
Don't use PHP short opening tags (<?). Use the long form (<?php). You risk getting tangled up in the wrong language processor.
You're looking for $_POST['createDir'] coming back from the form, but I don't see a form element with name="createDir".
What is $_POST['dirname'. var_dump($_POST)] supposed to do?
What is PATH?
Play it safe by giving a type= for dirname input element.

How to filter New WP Query by Custom Field Value?

I am creating new pages for each of my categories in wordpress. The post editor has a custom field that allows the selection of a sector type, this gets applied to the post on update. The custom field key is: sector, for custom field meta value options lets use SectorA, SectorB and SectorC. I am using a custom post type called projects.
I followed the advice at this link http://weblogtoolscollection.com/archives/2008/04/13/how-to-only-retrieve-posts-with-custom-fields/
How can I change the query line in the code below so that it filters the loop by a Sector name, lets use SectorA. I'll then reuse the code on each template page changing the value to SectorB and SectorC on the other pages.
I think this needs changing somehow:
$customPosts->query('showposts=5&sector=sectorA&post_type=projects' );
Currently it echos the sector value and description value successfully but is showing all the posts. So my attempt to limit it to sectorA using sector=sectorA doesn't seem to work?
This code is in functions.php:
function get_custom_field_posts_join($join) {
global $wpdb, $customFields;
return $join . " JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key in ($customFields)) ";
}
function get_custom_field_posts_group($group) {
global $wpdb;
$group .= " $wpdb->posts.ID ";
return $group;
}
And this code is on the Template Page:
<?php /* Begin Custom Field Posts */ ?>
<h2>Custom Posts</h2>
<ul>
<?php
global $customFields;
$customFields = "'sector', 'description'";
$customPosts = new WP_Query();
add_filter('posts_join', 'get_custom_field_posts_join');
add_filter('posts_groupby', 'get_custom_field_posts_group');
$customPosts->query('showposts=5&sector=sectorA&post_type=projects' );//Uses same parameters as query_posts
remove_filter('posts_join', 'get_custom_field_posts_join');
remove_filter('posts_groupby', 'get_custom_field_posts_group');
while ($customPosts->have_posts()) : $customPosts->the_post();
$sector = get_post_custom_values("sector");
$description= get_post_custom_values("description");?>
<li><?php echo $sector[0]; ?></li>
<li><?php echo $description[0]; ?></li><br />
<?php endwhile; ?>
</ul>
<?php /* End Custom Field Posts */ ?>
Thanks for your help
May be this what you want
function get_custom_field_posts_join($join) {
global $wpdb, $customSector;
return $join . " JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key = 'sector' and postmeta.value = '$customSector') ";
}
and modification of page
$customSector='sectorA';//<--- insert this
add_filter('posts_join', 'get_custom_field_posts_join');
Try using this code.
<?php
$sector = get_post_meta($post->ID, "sector", false);
if ($sector[0]=="") { ?>
<!-- If there are no custom fields, show nothing -->
<?php } else { ?>
<div class="sector">
<h3>Title</h3>
<?php foreach($sector as $sector) {
echo '<blockquote><p>'.$sector.'</p></blockquote>';
} ?>
</div>
<?php } ?>

Default checked checkboxes undefined in php

I am having trouble with checkboxes. What I am doing is displaying a list of checkboxes, if previously checked they will show the check mark, then you submit them and another php should recognize which were checked and which weren't. My script works fine for boxes previously unchecked, if you check them the action php recognizes it, but for boxes already checked I get Notice - undefined variable - for the boxes (even if unchecked/checked again). I really can't seem to find my way around this.
My code is
$ind=0; //counting variable
//generating checkboxes from an xml
foreach($xml as $checkbox)
{
$checks=$xml->checkbox[$ind]->active; //the active tag has a 0 or 1 stored.
echo "Activate ".$ind; // shows activate 0, activate 1, etc...
echo "<form name='checkb' action='show.php' method='post'>
echo "<input type='checkbox' name='checks[]' class='act' value='".$ind."'";
if($checks==0){ echo ">";} else{echo " checked ='checked'>";}
echo "<input type='hidden' name='ind' value=".$ind.">";
$ind=$ind+1;
echo "<input type='submit' name='sub' value='Submit'/> </form>"; }
On my action php I have
$chks = $_POST['checks'];
$N = count($chks);
echo("Active checkboxes ");
for($i=0; $i < $N; $i++)
{
echo($chks[$i] . " ");}
All this worked well until I decided to show if the boxes had been previously checked. So I guess the question is, why won't php recognize checked=checked as a true value? Or is there any other way to do this?
Thanks!
Seems like a lot of issues here.
Why are you outputting a form for each checkbox?
Where is your submit for the form?
You need a space in front of checked='checked' where you echo it out - echo " checked='checked'>"
If you move form output out of the loop, you will need to add your incremented value to the hidden input name property as well (or make it an array like checks, otherwise you will
only get one value for the field.
My attempt to try and clean it up a little.
$ind = 0;
echo "<form name='checkb' action='show.php' method='post'>";
foreach($xml as $checkbox){
echo "Activate $ind";
echo "<input type='checkbox' name='checks[]' class='act' value='$ind' ".(($checks == 0) ? " />" : " checked='checked' />";
echo "<input type='hidden' name='ind_$ind' value='$ind' />";
$ind++
}
echo "</form>";
Notice, like Mike said before that checked='checked' has the space before so that there is seperation between components. Also, your hidden elements all had the same names, so I added the $ind quantifier.
Hope this helps.

dojo file upload using zend framework problem

I am struggling with a bit of dojo that is needed to upload a file. Now the file upload form sits within a dojo dialog box, so is hidden until the user selects an 'upload file' button.
This button can be clicked on anywhere on the site, so I've created a controller to handle the upload.
At the moment I am just trying to get it to work, and in my head script I have the following:
<?php $this->headScript()->captureStart(); ?>
function sendForm(){
//Hide the file input field
dojo.style('inputField',"display","none");
//Show the progress bar
dojo.style('progressField',"display","inline");
dojo.byId('preamble').innerHTML = "Uploading ...";
dojo.io.iframe.send({
url: "<?php echo $this->baseUrl(); ?>/fileprocssing/loadfile/",
method: "post",
handleAs: "text",
form: dojo.byId('StartFrm'),
handle: function(data,ioArgs){
var fileData = dojo.fromJson(data);
if (fileData.status == "success"){
//Show the file input field
dojo.style(dojo.byId('inputField'),"display","inline");
dojo.byId('fileInput').value = '';
//Hide the progress bar
dojo.style(dojo.byId('progressField'),"display","none");
dojo.byId('uploadedFiles').innerHTML += "success: File: " + fileData.details.name
+ " size: " + fileData.details.size +"<br>";
dojo.byId('preamble').innerHTML = "File to Upload: ";
}else{
dojo.style(dojo.byId('inputField'),"display","inline");
dojo.style(dojo.byId('progressField'),"display","none");
dojo.byId('preamble').innerHTML = "Error, try again: ";
}
}
});
}
<?php $this->headScript()->captureEnd() ?>
With the the basic upload for like this
<form id="StartFrm" enctype="multipart/form-data"
name="cvupload"
action="<?php echo $this->baseUrl();?>/fileprocssing/loadfile/"
method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<!-- wrapping these in spans to be able to modify
parts of this form depending on what the
dojo.io.iframe.submit() does -->
<span id="preamble">File to Upload:</span><br>
<span id="inputField">
<input type="file" id="fileInput" name="uploadFile">
</span>
<span id="progressField" style="display:none;">
<div dojoType="dijit.ProgressBar" style="width:200px" indeterminate="true"></div>
</span>
<br/>
<button value="upload" dojoType="dijit.form.Button"
onclick="sendForm()">Upload</button>
</form>
What I would like to know is how I can get the JSON data object from /fileprocssing/loadfile/ that contains upload data information if the form is called from /somecontroller/someaction/ ?? and when the file has been processed automatically redirect to something like /fileprocesing/reviewdata/
At the moment the action that I have looks like this
public function loadfileAction() {
$log = Zend_Registry::getInstance()->get('log');
$log->log('in loadfileaction', Zend_Log::DEBUG);
$log->log($_FILES['uploadFile']['name'], Zend_Log::DEBUG);
$uploadedFile = array(
'details' => $_FILES['uploadFile'],
'status' => 'success'
);
$log->log($fileUploadData->toJson(), Zend_Log::DEBUG);
$foo = "{'status':'success',details: {name:'".
$_FILES['uploadFile']['name'].
"',size:".
$_FILES['uploadFile']['size'].
"}}";
$log->log($foo, Zend_Log::DEBUG);
$this->view->fileData = $foo;
}
I've handcrafted the JSON data for the time being but will use Zend_Dojo_Data but at the moment I am just trying to get this working.
I have to confess that I don't know dojo that well, but trying to get my head around it in the shortest possible time.
Thanks in advance.
dojo.io.iframe.send requires the response data to be wrapped in a TEXTAREA tag. This is the only/easiest cross browser way to successfully access and load the response data, and is a requirement. It looks like you are sending plain JSON back from the action.
You can also adjust your handleAs to be "json" and skip the intermediate dojo.fromJson(data) call, it will be passed to you as a JSON object (provided the response is wrapped in the aforementioned TEXTAREA)