Image uploader with preview didn't work - php

I have a single file named test.php. In this file, I written below codes to upload a picture (.PNG and .JPG). I also add some code to make a preview of pictures before being uploaded...
Nothing seems to be wrong but when I press the SUBMIT button, nothing happens...
Why? Where is my problem?
Update: I make changes and now I get this warning:
Warning: Invalid argument supplied for foreach() in...
test.php:
<script type="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<body>
<?php
if ( isset( $_POST[ 'submit' ] ) ) {
define ("UPLOAD_DIR" , "uploaded/pic/");
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
$info = getimagesize($_FILES["images"]["tmp_name"][$key]);
$image_type = $info[2];
$type = $_FILES['images']['type'][$key];
// if the image is .JPG or .PNG
if ( ($image_type == 3) || ($image_type == 2) ){
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $name);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($_FILES["images"]["tmp_name"][$key], UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
echo "<h2>Successfully Uploaded Images</h2>";
}
else{
echo "<h2>format not supported... </h2>";
}
}
}
}
?>
<div id="upload_form">
<form id="frm1" name="frm1" method="post" action="test.php" enctype="multipart/form-data">
<p>
<label for="images">insert your image</label>
<input type="file" name="images" id="images" tabindex="80"/>
</p>
<img id="pic" name="pic" src="#" />
<button type="submit" id="submit" name="submit">Upload Files!</button>
</form>
<script type="text/javascript" language="javascript">
// Preview the picture before Uploading on the server!
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#pic').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#images").change(function(){
readURL(this);
});
</script>
</div>

You need to put your name="images as an array using []
Like this:
<input type="file" name="images[]" id="images" tabindex="80"/>

Related

Notice: Undefined index: file when uploading file

I am trying to do a file check in an MVC framework, and even if I put the file with a jpg format, I am getting error
This is the function that checks the format
public function addAction()
{
$upload = new Upload();
if($this->request->isPost())
{
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed))
{
echo 'error';
}
$this->request->csrfCheck();
$upload->assign($this->request->get());
$upload->user_id = Users::currentUser()->id;
if($upload->save())
{
Router::redirect('upload');
}
}
$this->view->uploas = $upload ;
$this->view->displayErrors = $upload->getErrorMessages();
$this->view->postAction = PROOT . 'upload' . DS . 'add';
$this->view->render('upload/add');
}
And this is the HTML code:
<div class="col-lg-6 upload-position center" >
<input type="file" id="file" name="file" >
</div>
The isPost method checks if the form method is post
For the next one looking for it :)
To upload a file you will need enctype="multipart/form-data":
<form enctype="multipart/form-data">
<input type="file" name="file"/>
</form>

File upload with php issue moving file

I can't upload a file in my server using php. The problem is that I can't find see which is the error, or I don't know how see it. By the way, I think is something about the file moving. This is the php code
<!-- upload -->
<?php
if (isset($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
// File prop
$myFileName = $myFile["name"];
$myFileTmp = $myFile["tmp_name"];
$myFileSize = $myFile["size"];
$myFileError = $myFile["error"];
//File extension
$myFileExt = explode(".", $myFileName);
$myFileExt = strtolower(end($myFileExt));
$allowed = array ('png' , 'jpg' , 'txt');
if(in_array($myFileExt, $allowed)) {
if($myFileError === 0) {
$newFileName = uniqid('', true) . '.' .$myFileExt;
$fileDestination = "/var/www/upload".$newFileName;
if(move_uploaded_file($myFileTmp, $fileDestination)) {
print_r($fileDestination);
} else {
print_r($myFileError);
}
} else {
print_r("error");
}
} else {
print_r("error");
}
}
?>
Here is the form:
<form action="" method="post" enctype="multipart/form-data" style="margin:15px">
<input type="file" style="margin:5px" name="myFile">
<input type="submit" class="btn-upload-file" style="margin:5px" value="Upload">
</form>
Any idea?
Your issue is very Minor...
You just missed a Slash(/) after the /www/uploads.
Try this:
<?php
if (isset($_FILES["myFile"])) {
$myFile = $_FILES["myFile"];
// File prop
$myFileName = $myFile["name"];
$myFileTmp = $myFile["tmp_name"];
$myFileSize = $myFile["size"];
$myFileError = $myFile["error"];
//File extension
$myFileExt = explode(".", $myFileName);
$myFileExt = strtolower(end($myFileExt));
$allowed = array ('png' , 'jpg' , 'txt');
if(in_array($myFileExt, $allowed)) {
if($myFileError === 0) {
$newFileName = uniqid('', true) . '.' . $myFileExt;
$fileDestination = "/var/www/upload/{$newFileName}"; //YOU WERE ONLY MISSING A SLASH (/) HERE AFTER /upload
if(move_uploaded_file($myFileTmp, $fileDestination)) {
print_r($fileDestination);
} else {
print_r($myFileError);
}
} else {
print_r("error");
}
} else {
print_r("error");
}
}
?>
<form action="" method="post" enctype="multipart/form-data" style="margin:15px">
<input type="file" style="margin:5px" name="myFile">
<input type="submit" class="btn-upload-file" style="margin:5px" value="Upload">
</form>

Ajax upload script + file type filtering

I have an ajax upload script which i will post below. It will upload any file with any extention. I want it to only upload .png files but i dont know how to do that.
Here are my files:
<h1>Ajax File Upload Demo</h1>
<form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
Name it:
<input type="text" name="upload_name">
<br>
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
PHP:
<?php
$upload_name = $_POST['upload_name'];
$idx = strpos($_FILES['myfile']['name'],'.');
$ext = substr($_FILES['myfile']['name'],$idx);
$file_name = $upload_name . $ext;
$output_dir = "uploads/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
// move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
// echo "Uploaded File :".$_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$file_name);
echo "Uploaded File :" . $file_name;
}
}
?>
Sorry, i'm new and code blocks wont work for me. If someone could update, that would be great.
Client side
change your input file field this only works for modern browsers IE10+
Google Chrome 8.0+ and Firefox 4.0+
<input type="file" size="60" name="myfile" accept="image/png" />
PHP
$ext = pathinfo( $file_name , PATHINFO_EXTENSION );
if(strtolower($ext) == 'png' && $_FILES["file"]['type'] == "image/png")
{
// upload file
} else{
// not allowed
}
You can check file extension or mime type at server side.
// check extension
$info = new SplFileInfo($_FILES['myfile']['name']);
if ($info->getExtension() !== 'png') {
// return error
}
// or check file mime type
if (mime_content_type($_FILES['myfile']['name']) !== 'image/png') {
// return error
}
Example php:
$output_dir = "uploads/";
$upload_name = $_POST['upload_name'];
if(isset($_FILES["myfile"])) {
// Check upload errors
if ($_FILES["myfile"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
return;
}
// Check extensions
$info = new SplFileInfo($_FILES['myfile']['name']);
if ($info->getExtension() !== 'png') {
echo "Error: Only .png files are allowed";
return;
}
// Upload file
$file_name = $upload_name . $info->getExtension();
move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir . $file_name);
echo "Uploaded File :" . $file_name;
}

Uploading files in to Files folder

I want to upload files in to webroot/files folder, but my controller doing nothing, is there any mistake ?
View file name: uploadfile.ctp
Controller name: UploadFileController.php
Model name: UploadFile.php
In my view file I have:
<div class="files">
<input type="file" name="files[]" /><br/>
</div>
<button type="button" class="plus">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php echo $this->Html->script('addFile');
addFile script :
$(document).ready(function() {
$(".plus").click(function() {
$(".files").append("<input type='file' name='files[]'/><br/>");
});
});
And my Controller, I think that a mistake is somewhere here :
public function uploadFile() {
$uploadedFile = $this->request->params['UploadFile']['files[]']['tmp_name'];
$dir = WWW_ROOT . 'files/';
if ( !is_dir( $dir ) ) {
mkdir($dir);
chmod( $dir , 777);
}
$fileName = 'file_' . date( 'Y_m_d_h_i_s', time() );
move_uploaded_file( $uploadedFile, $dir. $fileName);
}
I got one Notice to:
Notice (8): Undefined index: UploadFile [APP\Controller\UploadFileController.php, line 7]
Thank you for any clue !
Solution
View File (uploadfile.ctp) :
<?php
echo $this->Form->create('uploadFile', array( 'type' => 'file'));
?>
<div class="input_fields_wrap">
<label for="uploadFilefiles"></label>
<input type="file" name="data[]" id="uploadFilefiles">
</div>
<button type="button" class="add_field_button">+</button> <br><br>
<form name="frm1" method="post" onsubmit="return greeting()">
<input type="submit" value="Submit">
</form>
<?php
echo $this->Html->script('addFile');
Controller (UploadFileController.php) :
class UploadFileController extends AppController {
public function uploadFile() {
$filename = '';
if ($this->request->is('post')) { // checks for the post values
$uploadData = $this->data;
//print_r($this->data); die;
foreach($uploadData as $file){
if ( $file['size'] == 0 || $file['error'] !== 0) { // checks for the errors and size of the uploaded file
return false;
}
$filename = basename($file['name']); // gets the base name of the uploaded file
$uploadFolder = WWW_ROOT. 'files'; // path where the uploaded file has to be saved
$filename = $filename; // adding time stamp for the uploaded image for uniqueness
$uploadPath = $uploadFolder . DS . $filename;
if( !file_exists($uploadFolder) ){
mkdir($uploadFolder); // creates folder if not found
}
if (!move_uploaded_file($file['tmp_name'], $uploadPath)) {
return false;
}
echo "Filename: $filename<br>";
}
}
}
}
Script (addFile.js) :
$(document).ready(function() {
var max_fields = 2;
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x <= max_fields){
x++;
$(wrapper).append("<div><input type='file' name='data[]' id='uploadFilefiles'/><button href='#' class='remove_field'>Kustuta</button></div>");
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on kustuta text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});

upload files using form Text input type

Presently I am using , type="file" for uploading files. But my use case is to upload from text box itself with given complete file path.
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
In submit form page:
<?php move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; ?>
I want to specify file path in a textbox , from there i want upload the image. How can i accomplish it ?
According to my knowledge you can't upload files with a textbox from the client's computer. Otherwise, it would be very easy to steal any file from the client, since textboxes are editable with JavaScript. I hope I understood your question correctly.
EDIT: Do you mean uploading from your computer, or from an URL? The second one can be accomplished.
Try this:
<?php
function h($str) {
return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}
if (
isset($_POST['path'], $_FILES['upfile']['error']) &&
is_int($_FILES['upfile']['error']) &&
is_string($_POST['path'])
) {
try {
$deep = 0;
foreach (explode('/', $_POST['path']) as $i => $hierarchy) {
if ($deep > 9) {
throw new RuntimeException('Hierarchy is too deep');
}
if ($hierarchy === '') {
if ($_POST['path'] !== '' && $i === 0) {
throw new RuntimeException('Absolute path is not allowed');
}
continue;
}
if ($hierarchy === '.') {
continue;
}
if (!preg_match('/\A(?!\.)[\w.-]++(?<!\.)\z/', $hierarchy)) {
throw new RuntimeException('Invalid directory name: ' . h($hierarchy));
}
if (!is_dir($hierarchy)) {
if (!mkdir($hierarchy)) {
throw new RuntimeException('Failed to create directory: ' . h($hierarchy));
}
$msgs[] = 'Created directory "' . h($hierarchy) . '"';
chmod($hierarchy, 0777);
}
chdir($hierarchy);
++$deep;
}
switch ($_FILES['upfile']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('File is not choosed');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('File is too large');
default:
throw new RuntimeException('Unknown error occurred');
}
if ($_FILES['upfile']['size'] > 1000000) {
throw new RuntimeException('File is too large');
}
if (!$info = getimagesize($_FILES['upfile']['tmp_name'])) {
throw new RuntimeException('Invalid image file');
}
if (false === array_search(
$info['mime'],
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
),
true
)) {
throw new RuntimeException('Unsupported image format');
}
if (!preg_match('/\A(?!\.)[\w.-]++(?<!\.)\z/', $_FILES['upfile']['name'])) {
throw new RuntimeException('Invalid filename: ' . h($_FILES['upfile']['name']));
}
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'],
$_FILES['upfile']['name']
)) {
throw new RuntimeException('Failed to save uploaded file');
}
$msgs[] =
'Uploaded successfully: ' .
($_POST['path'] === '' ? '.' : $_POST['path']) .
'/' .
$_FILES['upfile']['name']
;
} catch (RuntimeException $e) {
$msgs[] = $e->getMessage();
}
}
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
<title>Hierarchical Image Uploading</title>
</head>
<body>
<?php if (isset($msgs)): ?>
<ul>
<?php foreach ($msgs as $msg): ?>
<li><?=$msg?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<form enctype="multipart/form-data" method="post" action="">
<fieldset>
<legend>Select file (Directory name and filename must match <strong>'/(?!\A\.*+\z)\A(?!\.)[\w.-]++(?<!\.)\z/'</strong>)</legend>
Directory path: <input type="text" name="path" value=""><br />
Filename(JPEG, PNG, GIF): <input type="file" name="upfile"><br />
<input type="submit" value="Upload">
</fieldset>
</form>
</body>
</html>

Categories