Joomla 3.0 MVC file upload in custom component backend - php

SOLUTION: How to Save Uploaded File's Name on Database
this ended up helping me.
i am trying to add a file upload to a custom component using XML and database.
I know how to get file upload done in a static PHP environment but my knowledge
about the PHP MVC structure in joomla makes it so I am unable to add it.
What I have done so far:
• Added the field in the XML file (of the type file)
• Added the form fields in admin view project
• Added an extra field My_project table(same as the image upload column)
Until this point it works.(fields are shown in admin backend component)
Now when you save the document with a file uploaded in the admin back end it does not save it to the database.
if i put media as field type then it works, but when i change it to file it breaks down.
XML file
<?xml version="1.0" encoding="utf-8"?>
<form>
<fieldset>
<field name="project_file" type="file"
label="Upload file"
description="Upload file"
directory="mysites" />
<field name="main_image" type="media"
label="COM_MYSITES_FORM_LBL_PROJECT_MAIN_IMAGE"
description="COM_MYSITES_FORM_DESC_PROJECT_MAIN_IMAGE"
filter="raw"
directory="mysites" />
</fieldset>
PHP file upload script i normaly use
<?php
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
?>
but what part goes in the model and what part goes in the controller?
and how to call it.
entire view is called in the controller
class MysitesControllerProject extends JControllerForm {
function __construct() {
$this->view_list = 'projects';
$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform');
$file = $files['project_file'];
$this->upload($file);
parent::__construct();
}
public function upload($files)
{
$file_name = $files['name'];
$src = $files['tmp_name'];
$size = $files['size'];
$upload_error = $files['error'];
$type = $files['type'];
$dest = "/home/vol3/byethost33.com/b33_13467508/bim-portfolio.cu.cc/htdocs/tmp";
if (isset( $file_name)) {
// Move the uploaded file.
JFile::upload( $src, $filepath );
}
}
}

Placing new field in database and XML form is only half of work. You also have to write file save/upload functionality. There are two places you can do it. In controller (for example save task procedure) or model (there are 2-3 functions where you can do it). Look into this file /administrator/components/com_media/controllers/upload.php (upload procedure). I would just extend your save function so before data will be saved into database file will be stored on file system. You can find original save function declaration in /libraries/legacy/controller/legacy.php (for Joomla 3.0.1, for other versions it shouldn't be hard to find)
Here is sample save function:
public function save($key = null, $urlVar = null){
// youre file upload code
return parent::save($key = null, $urlVar = null)
}

Related

GET File extension on php

i have 2 fields on my project to upload documents(pdf, words) i use the following code to get the file extension on upload and rename the file with my custom name:
$ext= pathinfo($rsnew["File"], PATHINFO_EXTENSION);
my problem that i need to add to this code that, if one of the field if not update with a new document then it use the current extension of the oldrecord that was previous upload, and no change to blank extension
any idea, thanks in advance
using this code but no working
$ext= pathinfo($rsnew["File"], PATHINFO_EXTENSION);
$ext2= pathinfo($rsold["File"], PATHINFO_EXTENSION);
// $trim = substr($docpath,0,4);// not using now
if($_FILES["File"]["size"] == 0) {
$rsnew["File"] = "$rname $docpath1 $docpath2 " . " " . "$docpath ID$randomNumber" . ".$ext2";
} else {
$rnew["File"] = "$rname $docpath1 $docpath2 " . " " . "$docpath ID$randomNumber" . ".$ext";
return TRUE;
}
}

How to upload image and save URL in database in php

In this php code I want to customize the image upload destination. with this php file, I have directory called uploads. I want to add all my uploaded images to this directory and store path in db. how can I do this?
<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "image_upload";
$username_connect= "root";
$password_connect= "";
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
#mysql_select_db($database_connect) or die (mysql_error());
if($_POST) {
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file"]["error"] > 0) {
// if there is error in file uploading
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
// check if file already exit in "images" folder.
if (file_exists("images/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
//move_uploaded_file function will upload your image. if you want to resize image before uploading see this link http://b2atutorials.blogspot.com/2013/06/how-to-upload-and-resize-image-for.html
if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"])) {
// If file has uploaded successfully, store its name in data base
$query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
if(mysql_query($query_image)) {
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
} else {
echo 'File name not stored in database';
}
}
}
}
}
?>
currently when I run the upload
I am getting warnings
Warning: move_uploaded_file(images/1409261668002.png): failed to open stream: No such file or directory in D:\xampp\htdocs\image-upload\index.php on line 29
Warning: move_uploaded_file(): Unable to move 'D:\xampp\tmp\php1C1F.tmp' to 'images/1409261668002.png' in D:\xampp\htdocs\image-upload\index.php on line 29
You must specify a correct path, the 'images/1409261668002.png' path doesn't exist if you dont create them and don't specify them.
if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]))) { .... }
You must specify the absolute path
You can use below code:
$image=basename($_FILES['file']['name']);
$image=str_replace(' ','|',$image);
$tmppath="images/".$image;
if(move_uploaded_file($_FILES['file']['tmp_name'],$tmppath))
{...}
Let me know if you have any query/concern regarding this.

PHP Use of existing global search against uploaded files

I have included an upload script, which currently ONLY checks the upload folder to make sure that the file isn't there, which works just fine. However, I would like to somehow silently include a search function to see if it is already in one of the other directories.
The process: User uploads a prl, it checks upload folder if its there. This works. I need it to check another directory (recursively) to see if it is in any subdirectory already, and then list them out.
Just a note: $carrier is an existing subdirectory. I would like it to check the parent directory and all of its subs for the filename minus the extension, and if it exists, Error: this file already exists for "this" carrier.
<?php
$allowedExts = array("prl");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$carrier = $_POST['carrier'];
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
if (file_exists("./prls/" . $carrier . "/" . $_FILES["file"]["name"])){
echo "<h2><u>Error:</u></h2>";
echo $_FILES["file"]["name"] . " is already listed in the " . $carrier . " directory. ";
echo "<hr><br />If you feel this PRL is listed incorrectly, please let us know.";
die;
}
if (file_exists("upload/" . $_FILES["file"]["name"] . "-" .$carrier)) {
echo "<h2><u>Error:</u></h2>";
echo $_FILES["file"]["name"] . " for <b>" . $carrier . "</b> has already beeb submitted for approval. ";
die;
}
if ($_FILES["file"]["error"] == 0 && in_array($extension, $allowedExts))
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"] . "-" . $carrier);
echo "<h2><u>Submitted for approval:</u></h2>";
echo $_FILES["file"]["name"] . " for " . $carrier . ". <b>Thank you</b>.";
}
else
{
echo "Invalid file. Please choose a PRL with a \".prl\" extension.";
}
?>
You want to use RecursiveIteratorIterator. Here's a function that will behave like file_exists():
function file_exists_recursive($dir, $filename) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST );
foreach($iterator as $path) {
if (!$path->isDir()) {
if(file_exists($filename.$path->__toString()))
return true;
}
return false;
}
}
Then call this function in your file:
if (file_exists_recursive("upload/", $_FILES["file"]["name"] . "-" .$carrier)) {
echo "<h2><u>Error:</u></h2>";
echo $_FILES["file"]["name"] . " for <b>" . $carrier . "</b> has already beeb submitted for approval. ";
die;
}

retrieving image from database using php

<?php
$file= $_FILES["file"]["name"];//file selected in form
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
move_uploaded_file($_FILES["file"]["tmp_name"],
"c:/EasyPHP-12.1/www/new website/upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "c:/EasyPHP-12.1/www/new website/upload/" . $_FILES["file"]["name"];
if(($_FILES['file']['size'] >0))
{echo 'imagetrue';$con=mysql_connect('localhost','abc','YES') or die ("con");;
$db=mysql_select_db("website",$con) or die ("db");
$query=mysql_query("insert into website.picture (imagew) values ('$file')") or die('query'); //storing in db}
//echo $_FILES['file']['error'] ;
$query2= mysql_query("select * from website.picture");
$res=mysql_fetch_array($query2);
foreach($res as $row){
$str = "c:/EasyPHP-12.1/www/new website/upload/ ".$row['imagew'];
echo '<img src="'.$str.'" alt="no">' ;}
?>
i am using this script to store image and then displaying it on webpage but it is not working it only displays empty thumbnails...
I'd be very suspect about using absolute paths like c:/EasyPHP-12.1/www/new website/upload/
I'f you're then accessing the page from http://127.0.0.1/new-website (which I presume you are - or something similar) then having windows system pathnames could be a problem - do browsers even read the local filesystem like that ?
Also, it makes it very un-portable for when you move it to another server.
I'd suggest $str = 'upload/'.$row['imagew']; So it's relative to the document hosted in (I presume) 127.0.0.1/new website/image-viewer.php (or whatever you called it)
Check the return value of move_uploaded_file() - if it's false then it has failed. If that's failing try using the relative path :
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
This again presumes your script is sitting in 127.0.0.1/new-website
EDIT - NOTE ::: Is your form using enctype="multipart/form-data" ? If it's not then the images never get to the server !

I have this broken php upload script

I have this script for uploading a image and content from a form, it works in one project but not the other. I have spent a good few hours trying to debug it, I am hoping someone could point out the issue I might be having. Where there are comments is where I have tried to debug. The first error I got was the "echo invalid file" at the beginning of the last comment. With these specific areas commented out the upload name and type that I am supposed to be grabbing from the form is not being echoed, I am thinking this is where the error is occurring, but can't quite seem to find it. Thanks.
<?php
include("../includes/connect.php");
/*
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000))
{
*/
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
/* GRAB FORM DATA */
$title = $_POST['title'];
$date = $_POST['date'];
$content = $_POST['content'];
$imageName1 = $_FILES["file"]["name"];
echo $title;
echo "<br/>";
echo $date;
echo "<br/>";
echo $content;
echo "<br/>";
echo $imageName1;
$sql = "INSERT INTO blog (title,date,content,image)VALUES(
\"$title\",
\"$date\",
\"$content\",
\"$imageName1\"
)";
$results = mysql_query($sql)or die(mysql_error());
echo "<br/>";
if (file_exists("../images/blog/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../images/blog/" . $_FILES["file"]["name"]);
echo "Stored in: " . "../images/blog/" . $_FILES["file"]["name"];
}
}
/*
}
else
{
echo "Invalid file" . "<br/>";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
}
*/
//lets create a thumbnail of this uploaded image.
/*
$fileName = $_FILES["file"]["name"];
createThumb($fileName,310,"../images/blog/thumbs/");
function createThumb($thisFileName, $thisThumbWidth, $thisThumbDest){
$thisOriginalFilePath = "../images/blog/". $thisFileName;
list($width, $height) = getimagesize($thisOriginalFilePath);
$imgRatio =$width/$height;
$thisThumbHeight = $thisThumbWidth/$imgRatio;
$thumb = imagecreatetruecolor($thisThumbWidth,$thisThumbHeight);
$source = imagecreatefromjpeg($thisOriginalFilePath);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thisThumbWidth,$thisThumbHeight, $width, $height);
$newFileName = $thisThumbDest.$thisFileName;
imagejpeg($thumb,$newFileName, 80);
echo "<p><img src=\"$newFileName\" /></p>";
//header("location: http://www.google.ca");
}
*/
?>
Perhaps you forgot to add enctype="multipart/form-data" method="post" to your HTML form, or have no <input type="file" name="file" id="file" value=""/> in your HTML.
Here's some problems with your script:
The 'error' value in the $_FILES array is not just a boolean, it will tell you if an upload succeeded, or why it failed. The error codes are defined here.
The 'type' value is supplied by the remote client. It's NOT determined by the web server or PHP. As such, doing mime-type verification based on that value is a major hole: it's trivial to forge the supplied type value. Best to use a server-side method, like fileinfo, to determine the actual mime type.
You blindly insert the form data into your insertion query, which leaves you wide open to SQL injection attacks. At least pass the data through mysql_real_escape_string() before building your query, or better yet, use PDO and parameterized queries
You're storing the files with the original client-provided name. You at least check if the filename's already in use, preventing upload collisions/overwriting, but there's also the case where the client's operating system/file system allows characters in filenames that the server's OS/FS do not, which could lead to subtle file "vanished" bugs, or overwriting entirely different files because the invalid characters were filtered out or translated to something else. Since you're using a database to store information about the upload, you can store the original filename in that table, and use the table's primary key (an auto_increment int, right?) as the filename.
Not really a problem, but in terms of efficiency, there's no need to use getimagesize() in your thumb creation function. GD has imagesx() and imagesy() which get the pixel size from a GD image handle. getimagesize() is independent of GD, so you're opening and parsing the source image twice. Again, it's not really a problem, but on a busy site, opening the image only once could be a decent cpu time and memory usage savings.
The error was in the html form file, I had added a name="something" beside the method="post" and enctype="multi/form-data" obviously this was not liked. Thanks RC for pointing me in the right direction. I am not quite sure why I did this.
$_FILES["file"]["error"] is not just a flag.
It has error codes.
Explained in the manual

Categories