Joomla custom component adding browse button - joomla

I am developing a component in J! 2.5 and want to add a browse button on the backend so the user can pick a file they have previously uploaded. How would I go about this?

This is what I have come up with, if someone can make it more robust and reusable, that would be great. I may do it myself later, but for now I have an impossible deadline.
loadDir.php:
<?php
if(isset($_GET['dir'])) {
//Get array of valid extensions
if(isset($_GET['ext'])) {
if($_GET['ext'] == 'pdf') $validext = array("pdf");
else $validext = array("jpg", "jpeg", "png", "gif");
} else {
$validext = array("pdf", "jpg", "jpeg", "png", "gif");
}
$root = dirname(dirname(dirname(getcwd()))) . "/";
$directory = $root . $_GET['dir'];
$files = scandir($directory);
$thumb_count = 1;
//make sure we haven't gone too high (should never be called)
if(strpos($directory, 'images') == false) $directory = $root . "images";
//TODO: sort array with dirs in front
foreach($files as $file) {
if ($file == '.') continue; //Remove current directory from loop
//If in the images folder, don't let them go higher
if ($file == '..' & $_GET['dir'] == 'images') continue;
$path = $_GET['dir'];
if($file == '..') {
$path = dirname($path);
} else {
$path .= "/".$file;
}
if(is_dir($directory."/".$file)) {
echo "[DIR]".$file."".PHP_EOL;
} else {
//Check to see it's a valid extension
$ext = pathinfo($file, PATHINFO_EXTENSION);
$num = rand(0,100);
if(in_array($ext, $validext)) echo "[FILE]".$file."".PHP_EOL;
}
if(($thumb_count % 5) == 0) echo "<br/>";
$thumb_count++;
}
} else {
echo "Error loading: Directory not available";
}
?>
administrator/components/com_XXX/views/XXX/tmpl/form.php:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
selected_file = "";
function select(id, file) {
$('#' + id).css('background-color', 'red');
selected_file = file;
}
function loadDir(div, path, ext) {
$('#'+div+'Window').load('<?php echo JURI::root();?>administrator/components/com_lot/loadDir.php?div='+div+'&ext='+ext+'&dir='+path);
}
$(document).ready(function() {
$('#floorOpen').on("click", function(){
loadDir('floor', 'images', 'pdf');
$('#floorDialog').show();
});
$('#floorClose').on("click", function(){
$('#floorDialog').hide();
if(selected_file != "") $('#floor_plan').val(selected_file);
selected_file = "";
});
$('#floorCancel').on("click", function(){
$('#floorDialog').hide();
selected_file = "";
});
$('#mainOpen').on("click", function(){
loadDir('main', 'images', 'img');
$('#mainDialog').show();
});
$('#mainClose').on("click", function(){
$('#mainDialog').hide();
if(selected_file != "") $('#main_image').val(selected_file);
selected_file = "";
});
$('#mainCancel').on("click", function(){
$('#mainDialog').hide();
selected_file = "";
});
});
</script>
......
<div id="floorDialog" style="position:absolute;display:none;width:400px;height:300px;border:1px solid #c0c0c0;background-color:#f0f0f0;top:800px;left:400px;">
<div id="floorWindow" style="position:relative;width: 390px;height: 250px;margin: 4px;border: 1px solid #c0c0c0;">
</div>
CancelOK
</div>
<div id="mainDialog" style="position:absolute;display:none;width:400px;height:300px;border:1px solid #c0c0c0;background-color:#f0f0f0;top:800px;left:400px;">
<div id="mainWindow" style="position:relative;width: 390px;height: 250px;margin: 4px;border: 1px solid #c0c0c0;">
</div>
CancelOK
</div>
....
<tr>
<td width="100" align="right" class="key">
<label for="main_image">
<?php echo JText::_( 'Main Image' ); ?>:
</label>
</td>
<td>
<input class="text_area" type="text" name="main_image" id="main_image" size="32" maxlength="250" value="<?php echo $this->lotdata->main_image;?>" />Browse
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<label for="floor_plan">
<?php echo JText::_( 'Floor Plan' ); ?>:
</label>
</td>
<td>
<input class="text_area" type="text" name="floor_plan" id="floor_plan" size="32" maxlength="250" value="<?php echo $this->lotdata->floor_plan;?>" />Browse
</td>
</tr>
Basically I use AJAX to get a formatted list of files/directories. Then, using javascript we select the file we want and output the path on dialog close.

I think you can use the built in Joomla! form field filelist for this
<field name="myfile" type="filelist" default="" label="Select a file" description="" directory="administrator" filter="" exclude="" stripext="" />
Full options are:
The filelist form field type provides a drop down list of files from a specified directory. If the field has a saved value this is selected when the page is first loaded. If not, the default value (if any) is selected.
Params.filelist.jpg
By default, the first item on the list is '- Do not use -' (which is translatable) and is given the value '-1' and this is followed by '- Use default -' (also translatable) given the value '0'.
type (mandatory) must be filelist.
name (mandatory) is the unique name of the field.
label (mandatory) (translatable) is the
descriptive title of the field. directory (optional) is the
filesystem path to the directory containing the files to be listed.
If omitted the directory given by JPATH_ROOT is assumed.
default (optional) is the default file name.
description (optional)
(translatable) is text that will be shown as a tooltip when the user
moves the mouse over the drop-down box.
filter (optional) is a
regular expression string which is used to filter the list of files
selected for inclusion in the drop-down list. If omitted, all files
in the directory are included. The filter argument expression is
applied before the exclude argument expression. For information on
constructing regular expressions see Regular expressions in parameter
arguments.
exclude (optional) is a regular expression string which is
used to exclude files from the list. The exclude argument expression
is applied after the filter argument expression. For information on
constructing regular expressions see Regular expressions in parameter
arguments.
stripext (optional) is a Boolean argument. If true then
file name extensions will be stripped from the file names listed.
Also note that the file name will be saved without the extension too.
hide_none (optional) is a Boolean argument. If true, the '- Do not
use -' item is omitted from the drop-down list.
hide_default
(optional) is a Boolean argument. If true, the '- Use default -' item
is omitted from the drop-down list.
Here's where I got the list, I'm aware I'm not supposed to just link so I copied/pasted but I'll provide the original link in case the docs get updated.
https://docs.joomla.org/Filelist_form_field_type

Related

Having issues submitting form via AJAX on WordPress with reCAPTCHA

I've spent a good few hours trying to Google my way out of this, and I keep coming up with one issue or another. I'm getting myself wrapped up in knots and I am hoping that someone can help me by giving me a metaphorical slap around the face and showing me how the hell to do this properly.
Ok ... so I have a page on my front end that is inserted by a shortcode. This form is essentially a sort of AMA (Ask Me Anything) form, which I am using to create posts in my Admin area. Visitors enter their question, name and email, and submit the form to me via AJAX. The submissions are saved into the WordPress database under an ama custom post type, and an email is sent to me via wp_mail because I have an SMTP plugin installed that routes all requests for wp_mail through there. I have CMB2 installed on my website, and have keys for reCAPTCHA saved there.
So far, so good.
I had a working form with CMB2 fields, but CMB2 doesn't seem to support reCAPTCHA (otherwise it worked fine). So I decided to start from scratch and write my own form since it was just three fields that I wanted to submit. What could possibly go wrong, right?
Here's my Franken-code.
<?php
function ccdClient_shortcode_amaForm( $atts ) {
// Parse attributes
$atts = ( shortcode_atts( array(
'id' => uniqid('ccdClient_amaForm_'),
), $atts, 'ama_form' ) );
$rcKey = cmb2_get_option( 'ccdtheme_settings_apikeys', '_ccdclient_themesettings_apikeys_captcha_sitekey' );
$form = '
<form id="' . $atts['id'] . '" name="' . $atts['id'] . '" method="post" action="">
<div class="amaError"></div>
<div class="amaForm-field-question amaForm-field">
<p><label for="question">Your Question</label></p>
<p><textarea id="question" name="question" tabindex="1"></textarea></p>
</div>
<div class="amaForm-fieldGroup amaForm-groupTwo">
<div class="amaForm-field-name amaForm-field">
<p><label for="name">Your Name</label></p>
<p><input type="text" id="name" name="name" tabindex="2" /></p>
</div>
<div class="amaForm-field-email amaForm-field">
<p><label for="email">Your Email</label></p>
<p><input type="email" id="email" name="email" tabindex="3" /></p>
</div>
</div>
<div class="amaForm-fieldGroup amaForm-groupTwo">
<div class="amaForm-field-recaptcha amaForm-field amaForm-recaptcha">
<div class="g-recaptcha" data-sitekey="' . $rcKey . '"></div>
</div>
<div class="amaForm-field-submit amaForm-field amaForm-submit">
<input type="submit" value="Publish" id="submit" name="submit" />
</div>
</div>
</form>
<script>
$(document).ready(function() {
// Get form
var amaForm = $("#' . $atts['id'] . '");
// Get messages div
var amaError = $("#' . $atts['id'] . ' .amaError");
// Set data
var amaData = { "action" : "ama_form_process"}
var options = {
url: "'. admin_url( 'admin-ajax.php' ) .'",
type: "post",
dataType: "json",
data: amaData,
success : function(responseText, statusText, xhr, $form) {
$(amaError).html("Your form has been submitted successfully");
},
};
//Set submit function
amaForm.on("submit", function(e) {
//Prevent default form behavior
e.preventDefault();
// Serialise form data
//Post via AJAX
$.ajax(options)
.done(function(response) {
// Make sure that the amaError div has the "success" class.
$(amaError).removeClass("error");
$(amaError).addClass("success");
// Set the message text.
$(amaError).text(response);
})
.fail(function(data) {
// Make sure that the amaError div has the "error" class.
$(amaError).removeClass("success");
$(amaError).addClass("error");
// Set the message text.
if (data.responseText !== "") {
$(amaError).text(data.responseText);
} else {
$(amaError).text("Oops! An error occured, and your message could not be sent.");
}
});
});
});
</script>';
return $form;
}
add_shortcode('ama_form', 'ccdClient_shortcode_amaForm');
function ama_form_process() {
// If the form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Include WordPress files
include_once '../../../../../wp-includes/wp-load.php';
// Set reCaptcha private key
$recaptchaKey = cmb2_get_option( 'ccdtheme_settings_apikeys', '_ccdclient_themesettings_apikeys_captcha_secretkey' );
// If the Google Recaptcha box was clicked
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
$captcha = $_POST['g-recaptcha-response'];
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $recaptchaKey . "&response=" . $captcha);
$obj = json_decode($response);
// If the Google Recaptcha check was successful
if($obj->success == true) {
$question = strip_tags( trim( $_POST['question'] ) );
$name = strip_tags( trim( $_POST["name"] ) );
$name = str_replace( array("\r","\n"), array(" "," "), $name);
$email = filter_var( trim( $_POST["email"] ), FILTER_SANITIZE_EMAIL );
if ( !$name || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Add the content of the form to $post as an array
$post = array(
'post_title' => $question,
'post_status' => 'pending', // Could be: publish
'post_type' => 'ama', // Could be: `page` or your CPT
'meta_input' => array(
'_ccdclient_ama_name' => $name,
'_ccdclient_ama_email' => $email,
),
);
wp_insert_post($post);
echo 'Saved your post successfully! :)';
$recipient = get_option('admin_email');
$subject = "New question from $name";
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$question\n";
$email_headers = "From: $name <$email>";
wp_mail( $recipient, $subject, $email_content, $email_headers );
}
// If the Google Recaptcha check was not successful
else {
echo "Robot verification failed. Please try again. Success:" . $response;
}
}
// If the Google Recaptcha box was not clicked
else {
echo "Please click the reCAPTCHA box.";
}
}
// If the form was not submitted
// Not a POST request, set a 403 (forbidden) response code.
else {
echo "There was a problem with your submission, please try again.";
}
}
add_action("wp_ajax_ama_form_process", "ama_form_process");
//use this version for if you want the callback to work for users who are not logged in
add_action("wp_ajax_nopriv_ama_form_process", "ama_form_process");
As you can guess, I have looked at about a dozen or so pages and combined the efforts of each of them, thus overwriting parts that would perhaps have worked and confused myself no end, and so am resorting to here to preserve what is left of my sanity.
EDIT: Apologies. Whilst I copied the code, I wasn't specific on what issues I was facing. Goes to show the extent I was frustrated.
I have had a number of issues with this code. Currently, when I submit the form, it keeps the same URL but returns a 404 error page. However, it has previously told me that it cannot recognise functions - and therefore couldn't run - such as cmb2_get_option (which is a modification of get_option that specifically works with CMB2 options pages) and wp_insert_post. The latter error (ie: wp_insert_post) came up when the secret key was hard-coded into the script and not called from the get_option function.

strict with CGI::AJAX

I have set of code for updating a password in the table, here I'm using CGI::AJAX module to update the password and get the popup screen on corresponding execution.When using that code with my application it is executing properly but I didn't get the output(means Perl subroutine is not called when JavaScript function to get use.password is not updated into table). I don't get any error either.
#!/usr/bin/perl -w
use strict;
use CGI;
use DBI;
use Data::Dumper;
my $p = new CGI qw(header start_html end_html h1 script link);
use Class::Accessor;
use CGI::Ajax;
my $create_newuser;
my $ajax = new CGI::Ajax('fetch_javaScript' => $create_newuser);
print $ajax->build_html($p,\&Show_html,{-charset=>'UTF-8', -expires=>'-1d'});
sub Show_html
{
my $html = <<EOHTML;
<html>
<body bgcolor="#D2B9D3">
<IMG src="karvy.jpg" ALT="image">
<form name='myForm'>
<center><table><tr><td>
<div style="width:400px;height:250px;border:3px solid black;">
<center><h4>Create New Password's</h4>
<p>&nbsp User Name</b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<INPUT TYPE="text" NAME="user" id = "user" size = "15" maxlength = "15" tabindex = "1"/></p>
<p>&nbsp Password:</b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<INPUT TYPE=PASSWORD NAME="newpassword" id = "newpassword" size = "15" maxlength = "15" tabindex = "1"/></p>
<p>&nbsp Re-Password:</b>&nbsp&nbsp&nbsp<INPUT TYPE=PASSWORD NAME="repassword" id = "repassword" size = "15" maxlength = "15" tabindex = "1"/></p>
<input type="submit" id="val" value="Submit" align="middle" method="GET" onclick="fetch_javaScript(['user','newpassword','repassword']);"/><INPUT TYPE="reset" name = "Reset" value = "Reset"/>
<p>Main Menu <A HREF = login.pl>click here</A>
</center>
</div>
</td></tr></table></center>
</form>
</body>
</html>
EOHTML
return $html;
}
$create_newuser =sub
{
my #input = $p->params('args');
my $user=$input[0];
my $password=$input[1];
my $repassword=$input[2];
my $DSN = q/dbi:ODBC:SQLSERVER/;
my $uid = q/123/;
my $pwd = q/123/;
my $DRIVER = "Freetds";
my $dbh = DBI->connect($DSN,$uid,$pwd) or die "Coudn't Connect SQL";
if ($user ne '')
{
if($password eq $repassword)
{
my $sth=$dbh->do("insert into rpt_account_information (user_id,username,password,user_status,is_admin) values(2,'".$user."','".$password."',1,1)");
my $value=$sth;
print $value,"\n";
if($value == 1)
{
print 'Your pass has benn changed.Return to the main page';
}
}
else
{
print "<script>alert('Password and Re-Password does not match')</script>";
}
}
else
{
print "<script>alert('Please Enter the User Name')</script>";
}
}
my $create_newuser;
my $ajax = new CGI::Ajax('fetch_javaScript' => $create_newuser);
...;
$create_newuser =sub { ... };
At the moment when you create a new CGI::Ajax object, the $create_newuser variable is still undef. Only much later do you assign a coderef to it.
You can either assign the $create_newuser before you create the CGI::Ajax:
my $create_newuser =sub { ... };
my $ajax = new CGI::Ajax('fetch_javaScript' => $create_newuser);
...;
Or you use a normal, named subroutine and pass a coderef.
my $ajax = new CGI::Ajax('fetch_javaScript' => \&create_newuser);
...;
sub create_newuser { ... }
Aside from this main error, your script has many more problems.
You should use strict instead of the -w option.
For debugging purposes only, use CGI::Carp 'fatalsToBrowser' and sometimes even with warningsToBrowser can be extremely helpful. Otherwise, keeping a close eye on the error logs is a must.
my $p = new CGI qw(header start_html end_html h1 script link) doesn't make any sense. my $p = CGI->new should be sufficient.
use Class::Accessor seems a bit random here.
The HTML in Show_html is careless. First, your heredocs allows variable interpolation and escape codes – it has the semantics of a double quoted string. Most of the time, you don't want that. Start a heredoc like <<'END_OF_HTML' to avoid interpolation etc.
Secondly, look at that tag soup you are producing! Here are some snippets that astonish me:
bgcolor="#D2B9D3", align="middle" – because CSS hasn't been invented yet.
<center> – because CSS hasn't been invented yet, and this element isn't deprecated at all.
<table><tr><td><div ... </div></td></tr></table> – because there is nothing wrong with a table containing a single cell. (For what? This isn't even for layout reasons!) This table cell contains a single div …
… which contains another center. Seriously, what is so great about unneccessary DOM elements that CSS isn't even an option.
style="width:400px;height:250px;border:3px solid black;" – because responsive design hasn't been invented yet.
<p> ... </b> – Oh, what delicious tag soup!
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp – this isn't a typewriter, you know. Use CSS and proper markup for your layout. There is a difference between text containing whitespace, and empty areas in your layout.
tabindex = "1" … tabindex = "1" … tabindex = "1" – I don't think you know what tabindex does.
<A HREF = login.pl> – LOWERCASING OR QUOTING YOUR ATTRIBUTES IS FOR THE WEAK!!1
onclick="fetch_javaScript(['user','newpassword','repassword']);" – have you read the CGI::Ajax docs? This is not how it works: You need to define another argument with the ID of the element where the answer HTML is displayed.
In your create_newuser, you have an SQL injection vulnerability. Use placeholders to solve that. Instead of $sth->do("INSERT INTO ... VALUES('$foo')") use $sth->do('INSERT INTO ... VALUES(?)', $foo).
print ... – your Ajax handler shouldn't print output, instead it should return a HTML string, which then gets hooked into the DOM at the place your JS function specified. You want something like
use HTML::Entities;
sub create_newuser {
my ($user, $password, $repassword) = $p->params('args');
my ($e_user, $e_password) = map { encode_entities($_) } $user, $password;
# DON'T DO THIS, it is a joke
return "Hello <em>$e_user</em>, your password <code>$e_password</code> has been successfully transmitted in cleartext!";
}
and in your JS:
fetch_javaScript(['user','newpassword','repassword'], ['answer-element'], 'GET');
where your HTML document somewhere has a <div id="answer-element" />.

add submit to delete comment using ajax , php

Hi, I use a php code to view the all comments to any post from my sql and I want to add a submit button to every comment in order to delete it without refreshing the page, I mean using AJAX i don't know how to write that codes and connect it with html codes i want add submit like this :
<form>
<input type="submit" id="deletecomment">
</form>
and connected it with AJAX and delete.php page to delete the comment (ajax,delete.php)???????
this is my codes
$result = mysql_query ("select * from post_comments WHERE link ='$getlink' order by link asc");
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$link = $row['link'];
$time = $row['time'];
$content = nl2br($row['content']);
$name = ($row['link'] != '') ? '<h3 style="color:blue">'.$row['name'].'</h3>' : $row['name'];
$imge = $row['imge'];
echo '
<div class="commentuserbackground">
<img src="'.$imge.'" width="30px" height="30px">
<div id="comment-'.$id.'" class="username1">'.$name.'</div>
<div class="username2">'.$content.'</div><div class="commenttime"><h4 style="color:#5a5a5a">'.$time.'</h4>
</div></div>';
}
If you already have the jquery lib included in your html, you could do something like this:
# html page
<button data-id="1" class="delete_comment" /> # no need to wrap in form
# At the bottom of the body tag
$(".delete_comment").click(function(e){
e.preventDefault();
var $button = $(this), $comment = $button.parent(), id = $button.data("id");
$.ajax({
type: 'DELETE',
url: "/path/to/comment/" + id,
success: function(){ $comment.remove(); }
});
});

CodeIgniter & script.aculo.us InPlaceEdit produces duplicates on update

I'm working on a CI project and implemented scriptaculous InPlaceEdit. It works, but behaves strangly when and after updating a value.
1) When I click to edit, even though the field is just one word and should be 1 line, it produces a text area with 3 cols and 50 rows. It seems the script added empty space before the original value.
2) I save the new value and want to re-edit it, it gives me twice the form. after that 4x and so on...
HTML
So when the site is rendered, the line looks like this:
<h2 id="case_title-editme-27" class="editable savetitle" onclick="EditInput('case_title','27', 'cases');"> One line </h2>
Clicking to edit in place procudes:
<form id="case_title-editme-27-inplaceeditor" class="input-edit">
<textarea class="editor_field" rows="3" cols="40" name="value"></textarea>
<br>
<input class="editor_ok_button" type="submit" value="Save">
<a class="editor_cancel_link editor_cancel" href="#">cancel</a>
</form>
<h2 id="case_title-editme-27" class="editable savetitle" onclick="EditInput('case_title','27', 'cases');" title="Click to edit" style="display: none;"> One line </h2>
Here's my JS:
function EditInput(field, id, table) {
var id = id;
var table = table;
var field = field;
new Ajax.InPlaceEditor(
field+'-editme-'+id,
'<?PHP echo base_url();?>saveajax/'+id, {
okText: 'Save',
formClassName: 'input-edit',
callback: function(form, value) { return 'table=' + table + '&field=' + field + '&value=' + escape(value) },
}
);
}
And the PHP view
<?php foreach($caseheadlines as $headline):?>
<h2 class="editable savetitle" id="case_title-editme-<?php echo $headline['case_id']; ?>" onclick="EditInput('case_title','<?PHP echo $headline['case_id']; ?>', 'cases');">
<?php echo $headline['case_title']; ?>
</h2>
<?php endforeach;?>
So when clicking on the div, the js function get's fired and everything works expect the problems above. controller and models are fine, data get's saved to the DB.
Anyone has any idea?
The javascript you have provided is creating multiple inplace editors. I would change it like this.
for all the fields that you want to have editable add a specific class to those fields. I see you already have the editable class on the <h2> above - lets use that.
When the DOM is loaded trigger all those elements with that class to be inplace editors like this
document.observe("dom:loaded",function(){
$$('.editable').each(function(element){
new Ajax.InPlaceEditor(element,
'<?PHP echo base_url();?>saveajax/'+id, {
rows : 1,
cols : 15,
okText: 'Save',
formClassName: 'input-edit',
callback: function(form, value) { return 'table=' + table + '&field=' + field + '&value=' + escape(value) },
}
);
});
});
Now there will only be 1 instance of the inplace editor for each field. The inplace editor handles the on click turn into an editable field part.
as far as the row and cols problem if you set the rows and cols options in the instance for exactly what you want that should help - I've added them to my example

filename and contenttype of upload image

how to get the name of the file and the content type of the image which we uploaded in mvc application please tell me its urgent
thanks
ritz
May be below code will be helpful..
//index..
<?php
require_once("include/DBConnect.php");
include_once('header.php');
?>
<div align="center">
<h1 style="color:red">Welcome </h1>
<br/>
<form action="upload.php" method="post" enctype="multipart/form-data" id="UploadForm">
<input name="ImageFile" type="file" />
<input type="submit" id="SubmitButton" value="Upload" />
</form>
</div>
<?php include_once('footer.php');?>
//upload
<?php
require_once("include/DBConnect.php");
require_once("include/FunctionGeneral.php");
include_once('header.php');
if(isset($_POST))
{
$ThumbSquareSize = 200; //Thumbnail will be 200x200
$BigImageMaxSize = 500; //Image Maximum height or width
$ThumbPrefix = "thumb_"; //Normal thumb Prefix
$DestinationDirectory = 'uploads/'; //Upload Directory ends with / (slash)
$Quality = 90;
// check $_FILES['ImageFile'] array is not empty
if(!isset($_FILES['ImageFile']) || !is_uploaded_file($_FILES['ImageFile']['tmp_name']))
{
die('Something went wrong with Upload!'); // output error .
}
// Random number for both file, will be added after image name
$RandomNumber = rand(0, 9999999999);
// Elements (values) of $_FILES['ImageFile'] array
//let's access these values by using their index position
$ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name']));
$ImageSize = $_FILES['ImageFile']['size']; // Obtain original image size
$TempSrc = $_FILES['ImageFile']['tmp_name']; // Tmp name of image file stored in PHP tmp folder
$ImageType = $_FILES['ImageFile']['type']; //Obtain file type, returns "image/png", image/jpeg, text/plain etc.
switch(strtolower($ImageType))
{
case 'image/png':
$CreatedImage = imagecreatefrompng($_FILES['ImageFile']['tmp_name']);
break;
case 'image/gif':
$CreatedImage = imagecreatefromgif($_FILES['ImageFile']['tmp_name']);
break;
case 'image/jpeg':
case 'image/pjpeg':
$CreatedImage = imagecreatefromjpeg($_FILES['ImageFile']['tmp_name']);
break;
default:
die('Unsupported File!'); //output error and exit
}
//PHP getimagesize() function returns height-width from image file stored in PHP tmp folder.
list($CurWidth,$CurHeight)=getimagesize($TempSrc);
//Get file extension from Image name, this will be re-added after random name
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
//remove extension from filename
$ImageName = preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
//Construct a new image name (with random number added) for our new image.
$NewImageName = $ImageName.'-'.$RandomNumber.'.'.$ImageExt;
//set the Destination Image
$thumb_DestRandImageName = $DestinationDirectory.'thumbnail/'.$ThumbPrefix.$NewImageName; //Thumb name
$DestRandImageName = $DestinationDirectory.$NewImageName; //Name for Big Image
//Resize image to our Specified Size by calling resizeImage function.
if(resizeImage($CurWidth,$CurHeight,$BigImageMaxSize,$DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
//Create a square Thumbnail right after, this time we are using cropImage() function
if(!cropImage($CurWidth,$CurHeight,$ThumbSquareSize,$thumb_DestRandImageName,$CreatedImage,$Quality,$ImageType))
{
echo 'Error Creating thumbnail';
}
/*
At this point we have succesfully resized and created thumbnail image
We can render image to user's browser or store information in the database
For demo, we are going to output results on browser.
*/
echo '<div id="output">';
echo '<table width="100%" border="0" cellpadding="4" cellspacing="0">';
echo '<tr>';
echo '<td align="center"><img src="'.$thumb_DestRandImageName.'" alt="Thumbnail"></td>';
echo '</tr><tr>';
echo '<td align="center"><img src="'.$DestRandImageName.'" alt="Resized Image"></td>';
echo '</tr>';
echo '</table>';
echo '</div>';
/*
// Insert info into database table!
mysql_query("INSERT INTO myImageTable (ImageName, ThumbName, ImgPath)
VALUES ($DestRandImageName, $thumb_DestRandImageName, 'uploads/')");
*/
$added = getCurDate();
$title = "test";//$dbObj->escape_special_char($_POST['title']);
session_start();
$_SESSION['user_id'] = "rakhi";
$user_id = $_SESSION['user_id'];
$fields = "`photo_title` ,`createuser` ,`image_name` ,`added`";
$values = "'$title','$user_id','$NewImageName','$added'";
}else{
die('Resize Error'); //output error
}
}
include_once('footer.php');
?>

Resources