I made a separate page (following this guide) so he can upload pdf files (certificates of their products). And another page to the customer's search according to the selected product.
On the file upload page, the logic is as follows:
In a form:
Select the product (from a selector), and then select the certificate (pdf) to upload.
Submit button stored in a table (created by me) the product ID and the certificate name and attribute (soon to be able to do the search.)
In the database the data is saved correctly, but in the ftp folder files are not saved.
Here I show you my code in /themes/ theme /certificados.tpl
Form:
<form method="post" action="subirconnect.php" enctype="multipart/form-data">
<select id="producto" name="producto">
<option value="default" selected>Producto</option>
...
</select>
<select id="attr" name="attr">
<option value="default" selected>Diametro</option>
...
</select>
<input type="file" name="adjunto[]" multiple="multiple">
<input type="submit" value="Subir" name="enviar_certificados" class="btn btn-primary">
</form>
Validate form:
$TamanioMaximo=5000000; // 1000000 ~~~ 1mb
$CarpetaAlojamiento='../../certificados'; // path public_html/certificados
$NombreArchivoFinal="";
$MensajeCertificados="";
if(!empty($_POST['enviar_certificados'])) {
$name_producto = $_POST['producto'];
$name_combinacion = $_POST['attr'];
$name_certificados = $_FILES['adjunto']['name'];
$cntFiles = count($name_certificados);
for ($i=0; $i< $cntFiles; $i++) { //for multiples files
if($_FILES['adjunto']['size'][$i]>$TamanioMaximo) {
$MensajeCertificados= 'El archivo debe pesar menos de 5mb';
} else {
if (!is_dir($CarpetaAlojamiento)) {
mkdir($CarpetaAlojamiento);
chmod($CarpetaAlojamiento, 0777);
}
$NombreArchivoFinal=$CarpetaAlojamiento."/".$_FILES['adjunto']['name'][$i];
if(substr($_FILES['adjunto']['type'][$i],12,3) != 'pdf') {
$MensajeCertificados= 'Solo se permiten archivos .PDF';
} else if (is_uploaded_file($_FILES['adjunto']['tmp_name'][$i])) {
move_uploaded_file($_FILES['adjunto']['tmp_name'][$i], $NombreArchivoFinal);
$name_certificados = $_FILES['adjunto']['name'][$i];
/* upload data to db - works fine*/
SubirCertificados($cntFiles, $name_producto, $name_combinacion, $name_certificados);
$MensajeCertificados = '¡Certificado Subido!';
} else {
$MensajeCertificados= 'Problemas en el envío '.$_FILES['adjunto']['name'][$i];
}
}
}
}
The folder 'certificados' is already created and has the necessary permissions (777)
You may be missing? move_uploaded_file not working in prestashop?
This same code works fine on my localhost (WAMP)
Dont use static paths rather make folder in prestashop-root/upload/certificados
$CarpetaAlojamiento = _PS_UPLOAD_DIR_.'certificados';
Related
Lately, I have been working on an upload form. The idea is that users can upload their files to a remote FTP server. However, it does not work as expected.
Before I even start uploading the file, I get the following error: "Cannot move uploaded file to working directory". Again, I have not yet started uploading a file.
Here is my PHP code:
<?php
//FTP variabelen met de values
$host = "radioprogrammabank.nl";
$user = "***";
$pass = "***";
//location I want to send the uploaded file to (it is remote)
$destDir = "/domains/radioprogrammabank.nl/public_html/wp/wp-content/uploads";
$dehost = $_POST[$host];
$deuser = $_POST[$user];
$depass = $_POST[$pass];
$dedestDir = $_POST[$destDir];
$workDir = "\Users\stagiaire01\Uploads"; // definieer het lokale systeem
// get temporary file name for the uploaded file
$tmpName = basename($_FILES['file']['tmp_name']);
// copy uploaded file into the current directory
move_uploaded_file($_FILES['file']['tmp_name'], $workDir."/".$tmpName) or die('Cannot move uploaded file to working directory');
// maak connectie, als het niet werkt. Die en geef een melding
$conn = ftp_connect($host) or die ("Cannot initiate connection to host");
// send access parameters
ftp_login($conn, $user, $pass) or die("Cannot login");
// Voer de file upload uit
$upload = ftp_put($conn, $destDir."/".$_FILES['file']['name'], $workDir."/".$tmpName, FTP_BINARY);
// check upload status
// display message
if (!$upload) {
echo "Upload mislukt";
} else {
echo "Upload geslaagd";
}
// sluit de FTP connectie
ftp_close($conn);
// verwijder de lokale kopie van het bestand
unlink($workDir."/".$tmpName) or die("Cannot delete uploaded file from working directory -- manual deletion recommended");
?>
My HTML code:
<html>
<body>
<h2>U kunt hier uw album uploaden</h2>
<form enctype="multipart/form-data" method="post" action="upload.php">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000" />
File <br />
<input type="file" name="file" /><p />
<input type="submit" name="submit" value="Upload Album" />
</form>
</body>
[xyz-ips snippet="verbindftp"]
</html>
You may wonder why I have a shortcode in my HTML. The code is written in Wordpress. I use a plugin in which I can write PHP. The code works when writing this shortcode.
I have also tried doing a var_dump of $_FILES which tells me the following:
"array(0) { } Upload misluktCannot delete uploaded file from working directory -- manual deletion recommended"
I do not know why I get this message when doing a var_dump. I have set my host, username, password, and direction in my values above. The password and username are not shown because of security reasons.
I could not find any answers to this question on StackOverflow. However, I do hope I provided you with enough information to help me out. I expect to be able to upload a file to a remote FTP server.
Greetings,
Parsa_237
You need to check if an upload is occurring, otherwise, it will try to connect to the FTP server when the page is loaded, even if the user hasn't started uploading yet.
e.g.
if ( empty( $_FILES['file'] ) ) {
return;
}
As a side note, I notice you're using the PHP Snippets plugin, this plugin and others like it are incredibly dangerous. Instead, use add_shortcode in a PHP file to embed snippets of PHP inside of pages.
This is why you get this problem, the original tutorial assumed you would put the PHP code in a PHP file named upload.php, so it would only run when the form got submitted. But that's not the case with this plugin
Edit 2 : I notices user can upload unlimited files and can take all disk space, how to prevent that?
Edit: since no one answered this question, is there a source I could read to get my answer???
I have a contact form. There are three inputs. I used a jQuery plugin for uploading files. This plugin adds another form element and uploads files by ajax.
I'm kind of beginner but this code is for a customer and a real job so I want to make sure it's safe!
in my view:
<form action="" method="post" enctype="multipart/form-data" >
<input type="text" name="name" />
<input type="number" name="phone" />
<textarea name="enquiry" rows="10" ></textarea>
<div id="upload-div">
<div id="extraupload">Upload</div>
<input type="hidden" name="count" value="0" id="count"/>
<input type="submit" />
$(document).ready(function()
{
var uploadObj = $("#extraupload").uploadFile({
url:"/uplod_url",
fileName:"file",
onSuccess:function(files,data,xhr,pd)
{
data = jQuery.parseJSON(data);
if(data.status == 'success') {
var count = $('#count').val() * 1 + 1;
for(var i=0; i<data.files.length; i++) {
$('<input type="hidden" name="file_'+count+'" value="'+data.files[i]+'">').insertBefore('#extraupload');
$('#count').val(count);
count++;
}
}
},
});
});
</script>
each successful upload,will add one to input count value
and will append an hidden input with the value of uploaded file name.
In php I check for file type and change file name:
upload_url.php:
if ($_FILES['file']['type']=='image/jpeg' || $_FILES['file']['type']=='image/pjpeg') {
$ext = '.jpg';
}
elseif ($_FILES['file']['type']=='image/png') {
$ext = '.png';
}
elseif ($_FILES['file']['type']=='application/pdf') {
$ext = '.pdf';
}
else {
echo json_encode('Only images and pdf files are allowed!');
die();
}
$fileName = md5(uniqid());
$fileName = $fileName.$ext;
move_uploaded_file($_FILES["file"]["tmp_name"], 'image/tmp'.$fileName);
$result = array('status'=> 'success','files' => $fileName);
echo json_encode($result);
After changing the file's name to a unique hash, I save that in a tmp folder.
then when the main form is submitted this is what happens:
//validation method: if that file exists in tmp folder
if(isset($this->request->post['count']) && is_numeric($this->request->post['count'])) {
for($i=1; $i<=$this->request->post['count']; $i++ ) {
if(isset($this->request->post['file_'.$i])){
if(!file_exists('image/tmp/'.$this->request->post['file_'.$i])){
//throw error
}
} else{
//throw error
}
}
}
// hidden input count can only be integer
if(isset($this->request->post['count']) && !is_numeric($this->request->post['count'])) {
//throw error
}
and then mailing the file and saving file name in database(I did not include database part because I'm kind of sure it's ok)
//by every submition delete files in tmp folder older than 1 day
$oldFiles = glob($tmp_dir."*");
$now = time();
foreach ($oldFiles as $oldFile) {
if (is_file($oldFile)) {
if ($now - filemtime($oldFile) >= 60 * 60 * 24) {
unlink($oldFile);
}
}
}
$mail = new Mail();
//Mail Setting and details deleted
//if there's any file uploaded
if($this->request->post['count'] != 0) {
//unique directory for every form submition
$dir_path = 'image/submitted/'.uniqid();
mkdir($dir_path, 0764, true);
//for all hidden inputs move file from tmp folder to $dir_path
for ($i=1; $i <= $this->request->post['count']; $i++) {
$file = $this->request->post['file_'.$i];
rename('image/tmp'.$file, $dir_path.'/'.$file);
$mail->AddAttachment($dir_path.'/'.$file);
}
}
$mail->send();
now my question is: Is it safe this way? especially when I append hidden inputs with file's name and get the number of uploaded files from hidden input count??
This code already works, but I think this might be a security issue.
Thanks a lot for your patience and sorry for my poor english!
ps: I use opencart
There is the general misconception that in AJAX applications are more secure because it is thought that a user cannot access the server-side script without the rendered user interface (the AJAX based webpage). XML HTTP Request based web applications obscure server-side scripts, and this obscurity gives website developers and owners a false sense of security – obscurity is not security. Since XML HTTP requests function by using the same protocol as all else on the web (HTTP), technically speaking, AJAX-based web applications are vulnerable to the same hacking methodologies as ‘normal’ applications.
Let me describe my code first.
View:
<?php echo form_open_multipart('question_edit/update_question'); ?>
....
<div class="form-group">
<label for="ask_q" class="">A Brief Description of your question <em>(Optional)</em></label>
<textarea name="ask_q" id="ask_q"><?php echo $uposts->question_desc; ?></textarea>
</div>
<div class="form-group">
<label for="upld" class="">Upload New Docs <em>(Optional)</em></label>
<input type="file" name="upld[]" id="upld" style="width: 100%;" multiple>
</div>
....
<?php echo form_close(); ?>
Please note that my file input field is not mandatory. It is optional.
Controller:
function update_question(){
$update_data = array(
'question_desc' => $this->input->post('ask_q')
);
$this->ask_model->update_q($update_data);
if(!empty($_FILES['upld']['name'])){
$filesCount = count($_FILES['upld']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['userFile']['name'] = $_FILES['upld']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['upld']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['upld']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['upld']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['upld']['size'][$i];
$uploadPath = './uploads/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|jpeg|png|doc|docx|xls|xlsx|ppt|pptx|csv|ods|odt|odp|pdf|rtf|txt';
$config['max_size'] = '1048576';
$this->upload->initialize($config);
if(!$this->upload->do_upload('userFile')){
$this->session->set_flashdata('q_failure', 'Something went wrong. Please try again.');
redirect('/user-qa');
} else {
$fileData = $this->upload->data();
$uploadData[$i]['uploaded_file'] = $fileData['file_name'];
}
}
if(!empty($uploadData)){
//Insert files data into the database
$insert = $this->ask_model->insert_upload($uploadData);
}
}
$this->session->set_flashdata('q_success', '<div class="alert-message success">
<i class="icon-ok"></i>
<p><span>Success</span><br>
Your question has been updated successfully.</p>
</div>');
redirect('/user-dashboard');
}
My controller code describes (?) if file upload field is not empty, then upload file.
But the problem is each time I submit the form, it updates the database because of $this->ask_model->update_q($update_data); but giving the error message Something went wrong. Please try again. that I used for validating the $config.
I checked the log file. Log file states
You did not select a file to upload
It seems, my if(!empty($_FILES['upld']['name'])){ is not working.
UPDATE-1
I tried if(isset($_FILES['upld']) && $_FILES['upld']['size'] > 0){ instead of if(!empty($_FILES['upld']['name'])){ but the result is same.
My question is
Where is the problem ?
How to validate file size and file extension type ?
UPDATE-2
Tried if($_FILES['upld']['name']){ by seeing this stackoverflow Link but it is also not working.
the reason is when you submit an empty multiple form, it sends empty array with index 0
so we make sure that the first index is not empty
if(isset($_FILES['files']['name'])&&!empty($_FILES['files']['name'][0])):
hi i want to save image to mysql using php script and form html but in this code i see that the image is not sent to php can you help me please i am beginer in php.
Form.html
<form action="upload_image.php" method="post" enctype="multipart/form-data">
<p>
<input type="file" name="photo" />
<input type="submit" value="Submit" name="submit"/>
</p>
</form>
<b>
Afficher la premiere image de la base de donnes
</b>
php script :
<?php
echo ini_get( 'file_uploads' );
if($_SERVER['REQUEST_METHOD']=='POST'){
$con = mysqli_connect("localhost","root","","othmane");
if ($con->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$img = $_POST['photo'];
if($img!=null){
$sql = "INSERT INTO images (image) VALUES (?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"s",$img);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check == 1){
echo "Image Uploaded Successfully";
}else{
echo "Error Uploading Image";
}
}else{
echo "image not found";
}
mysqli_close($con);
}else{
echo "Error";
}
?>
Why is the image not sent to script ? i got always image not found in php.
The right way to access to file element by POST method is not $img = $_POST['photo']. You should use $_FILE var, for example $img = $_FILE['photo']['name'] to get the name of file.
There are some different info you can get from $_FILE var:
$_FILES['photo']['name']
The original name of the file on the client machine.
$_FILES['photo']['type']
The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['photo']['size']
The size, in bytes, of the uploaded file.
$_FILES['photo']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['photo']['error']
The error code associated with this file upload.
Look here: http://php.net/manual/en/features.file-upload.post-method.php
Pay attention: If you need to store the image in DB you need to convert file in binary data and store in DB as BLOB type.
Look here: http://dev.mysql.com/doc/refman/5.0/en/blob.html
As alternative, a good way is to store the file in a folder on your host and save the path in a DB.
This question already has answers here:
how to check if a $_FILE is set in php?
(5 answers)
Closed 8 years ago.
I have an input type ="file" in a form that upload images (multiple images) and other inputs (from textareas) .
I need that, if the user didn't choose any images, I don't want to excecute the upload image.
This because if I use the site from Ipad, the script give me error because he didn't find anything in the file-input[], also if I don't want to upload images.
So I wanna check if the file-input[] is empty or not, so the problem from Ipad will be solved (I hope).
This is the html
<div id="file-ins-immagini">
<div class="et-form-ins">Immagini allegate</div>
<input type="file" name="file-input[]" id="file-input" value="" class="file" multiple>
</div>
And this is the code of the insert in php ('invia' is the name of the submit button of my form)
if (isset($_POST['invia']) && $_POST['invia'] == "Inserisci")
{
$messaggiocaso = "";
$infoimages = array_combine($_FILES["file-input"]['name'], $_FILES["file-input"]['tmp_name']); // recuperiamo e uniamo le informazionei sulle immagini
foreach ($infoimages as $k => $v)
{
$nomefile = strtolower($k);
if(!empty($nomefile))
{
if (filesize($v) < $peso_file)
{
$estensionefile = pathinfo($nomefile, PATHINFO_EXTENSION);
if (in_array(strtolower($estensionefile), $estensioni))
{
if (is_uploaded_file($v))
{
if(!file_exists("$uploadDIR/$next_id"))
{
mkdir("$uploadDIR/$next_id",0777,true);
}
if (!move_uploaded_file($v, "$uploadDIR/$next_id/$nomefile"))
{
$messaggiocaso = urlencode("Impossibile l'inserimento del caso. Impossibile spostare il file $k");
header("location:tabella.php".'?msgcasoerrato='.$messaggiocaso);
exit;
}
else
//the rest of the code
I tryied with
if (isset($_POST['invia']) && $_POST['invia'] == "Inserisci" && !empty($_POST['file-input[]']))
and !empty($_POST['file-input']
but in these cases, the upload don't work anymore on pc.
So how can I check if file-input is empty?
if ($_FILES['file_input']){
foreach($_FILES['file_input']['name'] as $k=>$v){
if(!empty($_FILES['file_input']['name'][$k])){
if($_FILES['file_input']['size'][$k]>0){
// all ok, can be moved ..
}
}
}
}