It is technically possible in OpenCart 2.0 to change upload folder, where customers can upload files? Basically it is defined in config.php (both in root and admin folder) like this:
define('DIR_UPLOAD', '/home/www/shop/system/upload/');
It is possible simple change that destination (for example to another server)?
Currently i'm using this code (simply modified catalog/.../product/product.tpl):
<?php if ($option['type'] == 'file') { ?>
<!-- Button trigger modal -->
<button type="button" class="btn btn-default btn-block" data-toggle="modal" data-target="#myModal">
<i class="fa fa-upload"></i> <?php echo $button_upload; ?>
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel"><?php echo $button_upload; ?></h4>
</div>
<div class="modal-body embed-responsive">
<iframe height="300px" width="350px" frameborder="0" class="embed-responsive-item" src="captcha/captcha.php"></iframe>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
After success captcha, runs this index.php in iframe (ran on other server, which is a network attached storage with fix IP):
<!DOCTYPE html>
<html>
<body>
<form action="index.php?new_upload=true" method="post" enctype="multipart/form-data">
File to upload:
<input type="file" name="fileToUpload" id="fileToUpload"><input type="submit" value="Upload" name="submit">
</form>
<?php
if (isset($_GET['new_upload'])) {
upload();
}
function upload() {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0; break;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 10000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0; break;
}
// Allow certain file formats
if($fileType != "jpg" && $fileType != "png" && $fileType != "jpeg" && $fileType != "pdf" && $fileType != "JPG" && $fileType != "JPEG" && $fileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG, PDF & GIF files are allowed.";
$uploadOk = 0; break;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded."; break;
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
chmod($target_file, 0777); //change permission
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
</body>
</html>
This working fine, and you can easily upload files to server, but i look for a better solution. This didnt connect the order and the uploaded file, like opencart normally do.
Yes it would work, but you have to keep in mind some things.
The folder should he there.
The folder should have appropriate permissions.
It would work fine.
Related
I do this in my cms (Content Management System) in register section. I want to add profile image and I do like w3schools tuts: https://www.w3schools.com/php/php_file_upload.asp.
I do it ant=other file it can but when I run in my file I get an error:
Warning: Undefined array key "profileimg_regis" in C:\xampp\htdocs\DeknoinarakDev\dashboard\run\code.php on line 99
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\DeknoinarakDev\dashboard\run\code.php on line 99
Warning: Undefined array key "profileimg_regis" in C:\xampp\htdocs\DeknoinarakDev\dashboard\run\code.php on line 103
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\DeknoinarakDev\dashboard\run\code.php on line 103
Fatal error: Uncaught ValueError: Path cannot be empty in C:\xampp\htdocs\DeknoinarakDev\dashboard\run\code.php:103 Stack trace: #0 C:\xampp\htdocs\DeknoinarakDev\dashboard\run\code.php(103): getimagesize('') #1 {main} thrown in C:\xampp\htdocs\DeknoinarakDev\dashboard\run\code.php on line 103
This is my PHP code:
// Check if image file is a actual image or fake image
if(isset($_POST["register_btn"])) {
$target_dir = "img/user/";
$target_file = $target_dir . basename($_FILES["profileimg_regis"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$check = getimagesize($_FILES["profileimg_regis"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
}
else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["profileimg_regis"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
echo "Sorry, only JPG, JPEG & PNG files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}
else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
This is my HTML code:
<div class="modal-background" id="md-regisadmin">
<div class="modal-container">
<div class="modal">
<div class="modal-header">
<h2>Admin Account</h2>
<button onclick="closeModal(document.querySelectorAll('#md-regisadmin'))" type="button" id="dismiss-btn-modal">
<i class="fa fa-times" onclick="closeModal(document.querySelectorAll('#md-regisadmin'))" id="dismiss-btn-modal"></i>
</button>
</div>
<div class="md-content">
<div class="form-modal">
<div class="form-group md">
<form action="run/code.php" method="post">
<!--<label for="username_regis">Username:</label>
<input id="username_regis" type="text" name="username_regis" placeholder="Username" required/>
</div>
<div class="form-group md">
<label for="email_regis">E-mail:</label>
<input id="email_regis" type="email" name="email_regis" placeholder="Email" required/>
</div>
<div class="form-group md">
<label for="pwd_regis">Password:</label>
<input id="pwd_regis" type="password" name="pwd_regis" placeholder="Password" required/>
</div>
<div class="form-group md">
<label for="pwdr_regis">Repeat Password:</label>
<input id="pwdr_regis" type="password" name="pwdr_regis" placeholder="Repeat Password" required/>
</div>
<div class="form-group md">-->
<input id="profileimg_regis" name="profileimg_regis" type="file"/>
<!--</div>
<div class="form-group md">
<label for="utype_regis">Usertype:</label>
<select id="utype_regis" name="utype_regis"/>
<option value="noper">No Permission</option>
<option value="readonly">Reader</option>
<option value="mod">Moderator (Only Change Data In Website)</option>
<option value="admin">Administrator</option>
<option value="superadmin">Super Administrator</option>
<option value="godper">God Permission</option>
<option value="root">Root Administrator</option>
</select>
</div>
</div>
</div>-->
<div class="modal-footer">
<button type="submit" name="register_btn">
Add Admin Account
</button>
</form>
<button type="button" onclick="closeModal(document.querySelectorAll('#md-regisadmin'))" id="dismiss3-btn-modal">
<a onclick="closeModal(document.querySelectorAll('#md-regisadmin'))" id="dismiss2-btn-modal">Cancel</a>
</button>
</div>
</div>
</div>
</div>
Thanks if you can help. :)
Now I find How to fix it.
I forgot <form>enctype="multipart/form-data"</form> at the top of the form
Sorry. :)
I made a function to upload an image to my database and upload the image to a folder.
The url in the database changes to the url of the image but the file does not upload to the folder.
I get the error: Undefined index: user_image in image.php
Here is my code:
Image.php
<?php
$edit_row['opzoekImage'] = $_POST["user_image"];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if($imgFile)
{
$upload_dir = 'user_images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$userpic = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions))
{
if($imgSize < 5000000)
{
unlink($upload_dir.$edit_row['opzoekImage']);
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else
{
$errMSG = "Sorry, your file is too large it should be less then 5MB";
}
}
else
{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
else
{
$userpic = $edit_row['opzoekImage']; // old image from database
}
?>
New.php
<?php
if(isset($_POST["submit"]) && isset($_GET['website_naam']) && isset($_GET['tbl_name']) && $_GET['tbl_name'] == "tblOpzoek") {
include('config.php');
$website_naam = $_GET['website_naam'];
$sqlWebsiteId = "SELECT websiteId FROM tblWebsite WHERE websiteNaam = '$website_naam'";
if($db->query($sqlWebsiteId) != "") {
$resultWebsiteId = $db->query($sqlWebsiteId);
if ($resultWebsiteId->num_rows > 0) {
// output data of each row
while($row = $resultWebsiteId->fetch_assoc()) {
$websiteId = $row["websiteId"];
}
include('image.php');
$sqlToevoegenType = "INSERT INTO tblOpzoek (websiteId, opzoekName, opzoekValue, opzoekImage) VALUES ('".$websiteId."', '".$_POST["typeNaamToevoegen"]."', '".$_POST["typeWaardeToevoegen"]."', '".$userpic."')";
if($db->query($sqlToevoegenType) === TRUE) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sqlToevoegenType . "<br>" . $db->error."');</script>";
}
} else {
echo "0 results";
}
}
}
?>
My form:
Good to notice I do have more forms with file input name="user_image"
<!-- Type toevoegen-->
<div class="modal fade" id="addType" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="php/new.php?website_naam=<?php echo $websiteNaam ?>&tbl_name=tblOpzoek" method="post" id="formTypeToevoegen">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Type toevoegen</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Type Naam</label>
<input type="text" id="typeNaamToevoegen" name="typeNaamToevoegen" class="form-control" >
</div>
<div class="form-group">
<label>Type Waarde</label>
<input type="text" id="typeWaardeToevoegen" name="typeWaardeToevoegen" class="form-control" >
</div>
<div class="form-group">
<label>Type Afbeelding</label>
<input class="input-group" type="file" id="videoUploadFile" name="user_image" accept="image/*" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Sluiten</button>
<button type="submit" name="submit" class="btn btn-primary">Gegevens opslaan</button>
</div>
</form>
</div>
</div>
</div>
Thanks for your time!
You need to add the enctype attribute to your <form> tag
<form enctype="multipart/form-data">
As per your error first check what name you define in input tag because if you define different name in input tag and define different name in $_FILES then it shows error.
So define same name in input tag and $_FILES e.g.
$_FILES['user_image']['name'];
If above are correct then check whether you add enctype="multipart/form-data" in form or not.
I've been trying to solve why my file is not getting uploaded. I thought it was my school's permission causing error so I am running it over wampserver but I am still getting an undefined error and 'file was not uploaded'. I tried several echos, the file name is right, the directory is right and being create but the file will not upload to the directory. When I put it manually in the directory it uploads fine to my database so I have no idea what's wrong.
Outside of my header/body
<?php
session_start(); // Starting Session
require_once('config.php');
$link = mysqli_connect($db_host, $db_user, $db_pass, $db_name) or die ('Your DB connection is misconfigured. Enter the correct values and try again.');
//$query = mysqli_query(
?>
And here's the file upload:
<?php include 'navigation.php';?>
<h1> Welcome, <?php
echo $_SESSION['login_user']; ?> !</h1>
<!-- upload file script-->
<?php
if(!file_exists ("uploads/".$_SESSION['login_user'])){ //making the user directory
mkdir("uploads/".$_SESSION['login_user'], 0777, true);
}
$img_target_dir = "uploads/".$_SESSION['login_user']; //puts stuff in uploads
$target_file2 = $img_target_dir. basename($_FILES["imgfile"]["name"]); //img file
echo $_FILES["imgfile"]["name"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file2,PATHINFO_EXTENSION);
// Allow certain file formats for images (png)
// Check if image file is a actual image or fake image
if(isset($_POST['submit'])) {
if($imageFileType == "png") {
$check = getimagesize($_FILES["imgfile"]["tmp_name"]);
echo $img_target_dir . "/" . $_FILES["imgfile"]["name"];
if($check != false) {
if (move_uploaded_file($_FILES["imgfile"]["name"], $img_target_dir . "/" . $_FILES["imgfile"]["name"])) {
//chmod("uploads/img/lab2_upload.png",0777);
//echo "Image file size: ";
//echo filesize("uploads/img/lab2_upload.png") . "<br>";
//echo '<img src= "uploads/img/lab2_upload.png" height="300" width="300">';
}
else {
echo "file was not uploaded";
}
}
else {
echo "error uploading image";
}
}
else {
echo "File not png<br>";
}
}
?>
<!-- FORM FOR PHP UPLOAD -->
<section class="bg-primary" id="about">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 text-center">
<!-- Upload image-->
<h2> Image Upload </h2>
<h4> Ensure that the file upload is a PNG file!</h4>
<form action="profile.php" method="post" enctype="multipart/form-data">
<div><h2>Upload a PNG file: </h2>
<input class="btn btn-default btn-xl wow tada" id="imgfile" type="file" name="imgfile" value="imgfile">
<br>
<input class="btn btn-default btn-xl wow tada" id="Upload" type="submit" name="submit" value="Upload">
</div>
</form>
</div>
</div>
</div>
And a screenie: http://puu.sh/o7x1c/e3ee43d124.jpg
I have a problem. I'm able to upload some file but not all of them. In phpinfo, the upload_max_filesize is set to 64M. The file bigger than 3Mo doesn't send the $_POST["submit"] (when I do a var_dump)... And I got no error message...
var_dump($_POST);
if(ISSET($_POST["submit"])) {
while($rowSecteur=getRowElement($resultListeSecteur)){
if (ISSET($_FILES["fileToUpload".$rowSecteur['IDSecteur']])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload".$rowSecteur['IDSecteur']]["name"]);
$uploadOK = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(!empty($_FILES["fileToUpload".$rowSecteur['IDSecteur']]["tmp_name"])){
$check = getimagesize($_FILES["fileToUpload".$rowSecteur['IDSecteur']]["tmp_name"]);
if($check !== false) {
$uploadOK = 1;
include 'uploadPlan.php';
}
else {
$msg = '<div id="msg" class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
<h4 class="alert-heading">'._("Error!").'</h4>
<p>'. _("The file ' ").$_FILES['fileToUpload'.$rowSecteur['IDSecteur']]['name']._(" ' must be an image or the file size is incorrect.").'</p>
</div>';
$uploadOK = 0;
}
}
}
}
form code :
<form id="formMapSecteur" class="form-horizontal" method="post" action="selectMap.php">
<div id="fileBrowser<?php echo $rowSecteur['IDSecteur']?>" class="form-group form-inline col-sm-4">
<input type="file" name="fileToUpload<?php echo $rowSecteur['IDSecteur']?>" id="fileToUpload<?php echo $rowSecteur['IDSecteur']?>">
</div>
<div class="form-group form-inline col-sm-4 pull-right">
<button name="submit" type="submit" class="btn btn-primary"><?php echo _("Save")?></button>
</div>
</form>
Does someone understand what's going wrong in my code?
Here's the result of the var_dump when the file is smaller than 3Mo (exactly 2.85Mo) :
array (size=1)
'submit' => string '' (length=0)
and when the file is bigger than 3Mo (3.13Mo):
array (size=0)
empty
The post_max_size was set to 3M so I set it to 8M
Thanks to Tristan for the solution.
I'm trying to submit my Bootstrap form using php so that the data entered into the form is emailed to me from the page. Something somewhere is not working though, and unfortunately my php knowledge is lacking (and web searches have so far brought up nothing of use).
When you click submit the modal which the form is in instantly closes (a default HTML thing?). Re-opening the modal displays the the form error messages if you have left forms blank. If you submit the form with all the content present, nothing happens.
So my question is this: What have I done wrong, and how do I fix it to get the email to send? Also, can I stop the modal from closing when content is submitted but not complete?
EDIT: I have implemented the "correct" php for uploading an image, but it gives me an invalid file type even when they are valid. echo $target_file only returns the file_dir suggesting it is failing to ge the name of the file. What have I done wrong?
Here is the php:
<?php
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$location = $_POST['location'];
$desc = $_POST['desc'];
//Image upload
$target_dir = "/img/gallery/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists. Please rename your image.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
echo "Sorry, your file is too large. Google how to reduce an image size or contact us if you need help with this.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$from = 'Gallery Upload Form';
$to = 'email#example.com'; //I've only changed this for stackoverflow
$subject = 'New Gallery Image';
$body = "Name: $name\n Location: $location\n Description: $desc\n \n $file";
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
if (!$_POST['location']) {
$errLocation = 'Please enter where your image was taken';
}
if (!$_POST['desc']) {
$errDesc = 'Please enter a description of your image';
}
if (!$_POST['file']) {
$errFile = 'Please upload your image file';
}
// If there are no errors, send the email
if (!$errName && !$errName && !$errLocation && !$errDesc && $errFile) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success">Thank You! Your image has been submitted.</div>';
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later or report this to us.</div>';
}
}
}
?>
And here is the HTML:
<div class="box">
<h2>Upload your picture</h2>
<p>Upload your picture and we'll upload it to the gallery. The best picture each month will be featured as the page background. You can also upload your pictures to our Facebook page with
<font color="darkcyan">#gallery</font>.</p>
<br>
<!-- model content -->
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModalNorm">Upload a Picture</button>
<!-- Modal -->
<div class="modal fade" id="myModalNorm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h3 class="modal-title" id="myModalLabel">Upload Image</h3>
</div>
<!-- Modal Body -->
<div class="modal-body">
<form role="form" method="post" action="index.php">
<div class="form-group">
<label for="name">Your Name</label>
<input class="form-control" placeholder="John Smith" type="text" name="name" required value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
<div class="form-group">
<label for="location">Location</label>
<input class="form-control" placeholder="South-west bank of Trout Pool." type="text" name="location" value="<?php echo htmlspecialchars($_POST['location']); ?>">
<?php echo "<p class='text-danger'>$errLocation</p>";?>
</div>
<div class="form-group">
<label for="desc">Picture Description</label>
<textarea class="form-control" name="desc" rows="3" placeholder="A picture of a 6lbs trout, my biggest all season."><?php echo htmlspecialchars($_POST['desc']); ?></textarea>
<?php echo "<p class='text-danger'>$errDesc</p>";?>
</div>
<div class="form-group">
<label for="btn-upload">Upload Image File</label>
<input type="file" id="exampleInputFile" name="file" value="<?php echo htmlspecialchars($_POST['file']); ?>">
<?php echo "<p class='text-danger'>$errFile</p>";?>
</div>
<input id="submit" name="submit" type="submit" value="Upload" class="btn btn-primary">
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php echo $result; ?>
</div>
EDIT: A stupid question - Do you have to configure anything server-side for the email to be sent?
Your uploading a file your html form must have the enctype="multipart/form-data"
attribute.Use $_FILES variable to access information regarding uploaded file.
check these link for more information on $_FILES
http://php.net/manual/en/reserved.variables.files.php
http://www.tutorialsscripts.com/php-tutorials/php-files-variable.php