This code used to work and now I can't figure why it won't upload, I don't receive errors, I also don't receive any echo's or var_dumps back at all, it's simply like the button only refreshes the page. (Just for clarification there is alot more code doing alot of stuff, but this is the cause of my issue as I isolated it into another project with below code, which gave me the same results).
All it is meant to be doing is creating a folder named by the "ItemName", then it should be moving the images into that new named folder.
Thank you in advance, this problem has been hindering me for a few days now...
HTML PAGE
<form id="newsell" enctype="multipart/form-data" method="post">
<input type="text" class="css-input" name="ItemName" value="">
<input name="file[]" type="file" id="file" multiple />
<input type="submit" name="Upload" class="css-input1" value="Upload">
<?php
if ($_POST['Upload']) {
require_once("random.php");
}
?>
random.php
$MyLocation = "MyName"; // this comes from db, for this case just hardcode
$ItemName1 = htmlspecialchars($_POST["ItemName");
$ItemName = strip_tags($ItemName1);
$parentDir = "C:/wamp/www/HOME/uploadimages/".$MyLocation;
echo "Does it exist...." . $parentDir . "/" . $ItemName;
if(!is_dir($parentDir)) { // Check if the parent directory is a directory
echo "Apologies, something has gone wrong.";
RandError(); // POPUP
die();
}
if(!is_writable($parentDir)) { // Check if the parent directory is writeable
echo "Apologies, something has gone wrong.";
RandError(); // POPUP
die();
}
if(mkdir($parentDir . "/" . $ItemName) === false) { // Create the directory
echo "File apparently exists...." . $parentDir . "/" . $ItemName;
ExistingSaleName(); // POPUP
die();
}
// die('Created directory successfully'); // Success point
echo "AFTER INSERTION";
movefiles();
}
function movefiles() {
$MyLocation = "MyName";
echo "In movefiles";
$ItemName1 = htmlspecialchars($_POST["ItemName"]);
$ItemName = strip_tags($ItemName1);
extract($_POST);
if (extract($_POST) === null) { // trying to fault find here, but never returns anyway due to some kind of bug as at one point it was returning a null value
echo "PROBLEM...";
}
$error=array();
$extension=array("jpeg","jpg","png");
$res = ("C:/wamp/www/HOME/uploadimages/". $MyLocation. "/" . $ItemName);
foreach($_FILES["file"]["tmp_name"] as $key=>$tmp_name) {
$file_name=$_FILES["file"]["name"][$key];
$file_tmp=$_FILES["file"]["tmp_name"][$key];
if (!(($_FILES["file"]["type"][$key] == "image/png") || ($_FILES["file"] ["type"][$key] == "image/jpeg") || ($_FILES["file"]["type"][$key] == "image/jpg"))) {
die("Only the .jpg / .jpeg / .png file's were uploaded.");
} else {
echo "SHIT";
}
var_dump($file_tmp);
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
$count;
//check if file exist
if (!file_exists($res . "/" . $file_name)) {
sleep(2);
if (isset($_FILES["file"]["tmp_name"][$key])) {
move_uploaded_file($_FILES["file"]["tmp_name"][$key], $res);
++$count;
if ($count >=5) {
// go_to(); // This goes onto the next function
die ("First 5 images are uploaded, <br/> 5 images maximum.");
}
} else {
echo "It exited HERE...";
}
} else {
ExistingSaleName();
die();
}
}
}
I have create simple code to upload multiple images. Changes it yours.
<?php
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
$desired_dir="user_data";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
mysql_query($query);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple/>
<input type="submit"/>
Related
I need to upload several images, I have 2 problems, the first one that does not allow me to upload 2 or more files when it is from the cell phone (here something important, if it is from the cell phone you must open the camera and if it is in PC it must show the window of file selection, this works fine, but with the cell phone it only leaves one, so far I have only tried it on Android using Crhome) and the second detail is with the first element is not saved and if it is just a file because it does not either, it seems that it does not take position [0], when I put more than one image, the first does not save and the others are saved correctly. I've been trying for a while and I do not see the problem. Annex the structure of my files:
\camera
└───uploads
└───index.php
└───upload.php
index.php :
<html>
<head>
<meta charset="UTF-8">
<title>upload</title>
</head>
<body>
<form action="upload.php" method="post" multipart="" enctype="multipart/form-data">
<input type="file" name="img[]" accept="image/*" id="capture" capture="camera" multiple >
<input type="submit">
</form>
</body>
</html>
And upload.php :
<?php
echo '<pre>';
$img = $_FILES['img'];
if(!empty($img))
{
$img_desc = reArrayFiles($img);
print_r($img_desc);
foreach($img_desc as $val)
{
$newname = date('YmdHis',time()).mt_rand().'.jpg';
move_uploaded_file($val['tmp_name'],'./uploads/'.$newname);
}
}
function reArrayFiles($file)
{
$file_ary = array();
$file_count = count($file['name']);
$file_key = array_keys($file);
for($i=0;$i<$file_count;$i++)
{
foreach($file_key as $val)
{
$file_ary[$i][$val] = $file[$val][$i];
}
}
return $file_ary;
}
?>
This works for me, Hop this will solve your second problem.
if (isset($_FILES['Gallery']) && is_array($_FILES['Gallery'])) {
$errors= array();
foreach($_FILES['Gallery']['tmp_name'] as $key => $tmp_name ) {
$file_name = $key.$_FILES['Gallery']['name'][$key];
$file_size =$_FILES['Gallery']['size'][$key];
$file_tmp =$_FILES['Gallery']['tmp_name'][$key];
$file_type=$_FILES['Gallery']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
if (empty($errors)==true) {
if (is_dir('uploads')==false) {
mkdir('uploads', 0700); // Create directory if it does not exist
}
if (file_exists("uploads/".$file_name)==false) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
chmod("uploads/".$filename, 0777);
$Gallery_Link = "uploads/".$file_name;
} else { // rename the file if another one exist
$Gallery_Link = "uploads/".time()."_".$file_name;
rename($file_tmp,$Gallery_Link) ;
}
} else {
echo $errors;
}
}
}
For me to easy browse the right file before uploading, this what i want to accomplish. How to do that?
My input codes:
Inside the form are two inputs. And with likely similar filename. Submit button will trigger the "uploadnow" function.
<td>UPLOAD#1: AGL_001.txt <input type="file" name="upload1" id="upload1"></td>
<td>UPLOAD#2: AGL_0001.txt <input type="file" name="upload2" id="upload2"></td>
function uploadnow(){
$allowed_upload1 = ['AGL_001.txt']; // added
$allowed_upload2 = ['AGL_0001.txt']; //added
if(isset($_FILES['upload1']['name'])){
//$errors= array();
$file_name = $_FILES['upload1']['name'];
$file_size =$_FILES['upload1']['size'];
$file_tmp =$_FILES['upload1']['tmp_name'];
$file_type=$_FILES['upload1']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['upload1']['name'])));
//$img_loc = $file_name.'.'.$file_ext;
if (in_array($file_name, $allowed_upload1)) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
} else {
$message = "Sorry, wrong filename on UPLOAD#1";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
if(isset($_FILES['upload2']['name'])){
//$errors= array();
$file_name = $_FILES['upload2']['name'];
$file_size =$_FILES['upload2']['size'];
$file_tmp =$_FILES['upload2']['tmp_name'];
$file_type=$_FILES['upload2']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['upload2']['name'])));
//$img_loc = $file_name.'.'.$file_ext;
if (in_array($file_name, $allowed_upload2)) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
} else {
$message = "Sorry, wrong filename on UPLOAD#2";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
}
I believe you can't preset the filename client-side, but you can constrain accepted file types with accept attribute on your input (thought it's tough to predict all mime types .txt comes with):
<input type="file" accept="text/plain">
or more general
<input type="file" accept="text/*">
Though this is not a bullet proof solution and you can foul the browser.
You can implement a JavaScript solution, which will listen to input changes and validate filename.
To do it server side, just check the value of $_FILES[$input_name]['name'] (or $_FILES[$input_name][$index]['name'] for a file input with multiple attribute)
$allowed_filenames = [
'AGL_001.txt',
];
if(isset($_FILES['upload1']['name'])){
//$errors= array();
$file_name = $_FILES['upload1']['name'];
$file_size =$_FILES['upload1']['size'];
$file_tmp =$_FILES['upload1']['tmp_name'];
$file_type=$_FILES['upload1']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['upload1']['name'])));
//$img_loc = $file_name.'.'.$file_ext;
if (in_array($file_name, $allowed_filenames)) {
move_uploaded_file($file_tmp,"uploads/".$file_name);
} else {
// log an error
}
}
Am doing multiple file upload in the controller but the file doesn't get uploaded
controller code: for the upload
$images = $_FILES['evidence'];
$success = null;
$paths= ['uploads'];
// get file names
$filenames = $images['name'];
// loop and process files
for($i=0; $i < count($filenames); $i++){
//$ext = explode('.', basename($filenames[$i]));
$target = "uploads/cases/evidence".DIRECTORY_SEPARATOR . md5(uniqid()); //. "." . array_pop($ext);
if(move_uploaded_file($images['name'], $target)) {
$success = true;
$paths[] = $target;
} else {
$success = false;
break;
}
echo $success;
}
// check and process based on successful status
if ($success === true) {
$evidence = new Evidence();
$evidence->case_ref=$id;
$evidence->saved_on=date("Y-m-d");
$evidence->save();
$output = [];
} elseif ($success === false) {
$output = ['error'=>'Error while uploading images. Contact the system administrator'];
foreach ($paths as $file) {
unlink($file);
}
} else {
$output = ['error'=>'No files were processed.'];
}
// return a json encoded response for plugin to process successfully
echo json_encode($output);
I have tried var_dump($images['name'] and everything seems okay the move file does not upload the file
Check what you obtain in $_FILES and in $_POST and evaluate your logic by these result...
The PHP manual say this function return false when the filename is checked to ensure that the file designated by filename and is not a valid filename or the file can be moved for some reason.. Are you sure the filename generated is valid and/or can be mooved to destination?
this is the related php man php.net/manual/en/function.move-uploaded-file.php
Have you added enctype attribute to form tag?
For example:
<form action="demo_post_enctype.asp" method="post" enctype="multipart/form-data">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
I would like to show the errors next to input field. I tried echoing the error but it just displays the word Array. How can I show the error next to input field? Also I would like to let the user upload 5 photos and only the first photo is required. I mean the user can upload 5 photos but all the 5 photos aren't required only one. is that possible? thanks
<?php
$out['error'][]=''; //this is what I added
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {
//Config Section
//Set file upload path
$path = 'productpic/'; //with trailing slash
//Set max file size in bytes
$max_size = 2097152;
//Set default file extension whitelist
$whitelist_ext = array('jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
//The Validation
// Create an array to hold any output
$out = array('error'=>null);
if (!$file_field) {
$out['error'][] = "Please specify a valid form field name";
}
if (!$path) {
$out['error'][] = "Please specify a valid upload path";
}
if (count($out['error'])>0) {
return $out;
}
//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
// Get filename
$file_info = pathinfo($_FILES[$file_field]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$out['error'][] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
$out['error'][] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$file_field]["size"] > $max_size) {
$out['error'][] = "We are sorry, the image must be less than 2MB";
}
//If $check image is set as true
if ($check_image) {
if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
$out['error'][] = "The file you trying to upload is not an Image, we only accept images";
}
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$out['error'][] = "The image you trying to upload already exists, please upload only once";
}
if (count($out['error'])>0) {
//The file has not correctly validated
return $out;
}
if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
//Success
$out['filepath'] = $path;
$out['filename'] = $newname;
return $out;
} else {
$out['error'][] = "Server Error!";
}
} else {
$out['error'][] = "Please select a photo";
return $out;
}
}
?>
<?php
if (isset($_POST['submit'])) {
$file = uploadFile('file', true, false);
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message .= '<p>'.$msg.'</p>';
}
} else {
$message = "File uploaded successfully";
$sub=1;
}
echo $message;
}
?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<?php
ini_set( "display_errors", 0);
if($sub==0)
{
?>
<input name="file" type="file" size="20" /><span><?php echo $out['error'] ;?></span> //It displays here just the word Array
<input name="submit" type="submit" value="Upload" />
<?php
}
?>
</form>
Because $out['error'] is an array, echoing it will output Array, as you noticed. To output it as a string you'll need to convert it first; one option to do so is using implode. I'd suggest using <br> as the 'glue' so that each error will show on a different line.
So,
<input name="file" type="file" size="20" /><span><?php echo implode('<br>', $out['error']) ;?></span>
<input name="submit" type="submit" value="Upload" />
However, perhaps a better solution would be to store the error as a string ($out['error'] = 'There was an error' rather than $out['error'][] = 'There was an error') and using a proper control structure to ensure that once an error is found the validation check ends and the form with the error message is output.
For the control structure you could do:
if ($first_check)
{
$out['error'] = 'First error message';
}
elseif ($second_check)
{
$out['error'] = 'Second error message';
}
else
{
$out['success'] = 'Success message';
}
am having some trouble with PHP on the webserver I am using.
I am sure the answer is obvious but for some reason it is eluding me completely.
I have a php file which uploads two files, a before and an after shot of the client.
The script on my server(localhost) works fine, it uploads the files, renames the files to a timestamp and puts the images into there folders for further sorting by another script.
Yet when I upload it to the webserver, and some files work (i.e mel.jpg, test.jpg) but files like IMG_0042.jpg do not work, Im sure the answer is something simple, but is completely eluding me.
Im thinking the underscore may have something to do with it, but cannot for the life of my figure it out, any help greatly appreciated,
thanks very much.
<?php
if(!isset($_COOKIE['auth'])) {
header("Location: login12.php");
exit();
}
$page_title="test";
include('header.html');
// Upload and Rename File
if (isset($_POST['submitted'])) {
$filenamebef = $_FILES["uploadbef"]["name"];
$filenameaft = $_FILES["uploadaft"]["name"];
$file_basename_bef = substr($filenamebef, 0, strripos($filenamebef, '.'));
$file_basename_aft = substr($filenameaft, 0, strripos($filenameaft, '.'));
// get file extention
$file_ext_bef = substr($filenamebef, strripos($filenamebef, '.'));
$file_ext_aft = substr($filenameaft, strripos($filenameaft, '.'));
// get file name
$filesize_bef = $_FILES["uploadbef"]["size"];
$filesize_aft = $_FILES["uploadaft"]["size"];
$allowed = array('image/pjpeg','image/jpeg','image/JPG','image/X-PNG','image/PNG','image /png','image/x-png');
if ((in_array($_FILES['uploadbef']['type'], $allowed)) && in_array($_FILES['uploadaft']['type'], $allowed)) {
if (($filesize_bef < 200000) && ($filesize_aft < 200000)){
// rename file
$date = date("mdy");
$time = date("His");
$timedate = $time . $date;
$newfilenamebef = $timedate . $file_ext_bef;
$newfilenameaft = $timedate . $file_ext_aft;
if ((file_exists("upload/images/before" . $newfilenamebef)) && (file_exists("uploads/images/after" . $newfilenameaft))) {
// file already exists error
echo "You have already uloaded this file.";
} else {
move_uploaded_file($_FILES["uploadbef"]["tmp_name"], "uploads/images/before/" . $newfilenamebef) && move_uploaded_file($_FILES["uploadaft"]["tmp_name"], "uploads/images/after/" . $newfilenameaft);
echo "File uploaded successfully.";
}
}
} elseif ((empty($file_basename_bef)) && (empty($file_basename_aft))) {
// file selection error
echo "Please select a file to upload.";
} elseif (($filesize_bef > 200000) && ($filesize_aft > 200000)) {
// file size error
echo "The file you are trying to upload is too large.";
} else {
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed);
unlink($_FILES["uploadbef"]["tmp_name"]);
unlink($_FILES["uploadaft"]["tmp_name"]);
}
}
echo $newfilenamebef;
echo $newfilenameaft;
?>
<form enctype="multipart/form-data" action="uploading.php" method="post">
<input type="hidden" value="MAX_FILE_SIZE" value="524288">
<fieldset>
<legend>Select a JPEG or PNG image of 512kb or smaller to be uploaded : </legend>
<p><b>Before</b> <input type="file" name="uploadbef" /></p>
<p><b>After</b> <input type="file" name="uploadaft" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
<?php
include('footer.html');
?>
You should but these two lines at the top of your index.php or bootstrap.php :
error_reporting( -1 );
ini_set( "display_errors" , 1 );
And see if some error messages turn up.
It is quite possible that problem is caused by wrong file permissions.
At a quick guess I would say that your localhost is not case sensitive, whereas your webserver is.
In other words, on your localhost IMG_12345.JPG is the same as img_12345.jpg. On your webserver, though, they are treated differently.
Without any actual reported errors, it's hard to be certain, but this is a common problem.
You're not checking for valid uploads properly. Something like the following would be FAR more reliable:
// this value is ALWAYS present and doesn't depend on form fields
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errmsgs = array();
if ($_FILES['uploadbef']['error'] !== UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadebef' failed with code #" . $_FILES['uploadebef']['error'];
}
if ($_FILES['uploadaft']['error'] === UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadeaft' failed wicode #" . $_FILES['uploadeaft']['error'];
}
if (count($errmsgs) > 0) {
print_r($errmsgs);
die();
}
... process the files here ...
}
As well, why re-invent the wheel to split up the file names?
$parts = path_info($_FILES['uploadaft']['name']);
$basename = $parts['basename'];
$ext = $parts['extension'];