Pass $_FILE data to $.getJSON - php

I want to pass the $_FILES array to .getJSON.
Here is my jquery:
$.getJSON(link+'api/images/upload.php',{action:'image.upload',id:id,img:img}, function (response){
var url = this.url;
var result = response.message;
if(response.status == 200){
var data = response.data;
console.log(data);
try_print('Data',data,try_dbg);
}
else{
alert(response.message);
}
});
Here is my api:
switch($_REQUEST['action']){
case 'image.upload':
$id = $_REQUEST['id'];
$img = $_FILES['img']['name']; //echo $img;
$temp = explode(".", $_FILES["img"]["name"]);
$extension = end($temp);
$error = $_FILES["img"]["error"];
if(!empty($id)){
if(!empty($img)){
if(is_writable($original)){
if(in_array($extension, $allowedExts)){
if($error == 0){
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize($filename);
$a = apiPicture($original, $id, $_FILES["img"]);
$return['status'] = 'success';
$return['url'] = $original.$_FILES["img"]["name"];
$return['width'] = $width;
$return['height'] = $height;
$return['status'] = 200;
$return['message'] = 'Success.';
}
else{
$return['status'] = 400;
$return['message'] = 'Error: '.$error;
}
.... the rest of the error codes
break;
default:
$return['message'] = 'Unknown Request';
}
Is there a solution for this, can I pass an image through .getJSON?

Related

Flutter: Scanned 'Path' On Null

I'm trying to upload an image taken using the image picker package to my localhost server using a PHP API.
When the picture is taken, a message in the debug console appears saying "scanned (some path) to null" and the image path isn't saved.
I'd be very grateful if anyone who knows anything about this fills me in on how I can fix it. thank you in advance!
Here's my Relevant code:
-(PHP Backend)inserting an image to the database:
include_once "../../api/patients/create_image.php";
if (
isset($_POST["id"])
) {
if (!empty($_FILES["file"]['name']) )
{
$image = uploadImage("file", '../images/', 200,600);
$img_image = $image["image"];
}
else{
$img_image = "";
}
$id = $_POST["id"];
$insertArray = array();
array_push($insertArray, htmlspecialchars(strip_tags($img_image)));
array_push($insertArray, htmlspecialchars(strip_tags($id)));
$sql = "insert into patient_images (image, file_id) values (?,?)";
$result = dbExec($sql, $insertArray);
$resJson = array("result" => "success", "code" => 200, "body" => $insertArray);
echo json_encode($resJson, JSON_UNESCAPED_UNICODE);
} else {
//bad request
$resJson = array("result" => "fail", "code" => "400");
echo json_encode($resJson, JSON_UNESCAPED_UNICODE);
}
unction uploadImage($inputName, $uploadDir , $thumbnail_width , $image_width)
{
$image = $_FILES[$inputName];
//echo "error " . $image['name'] . $image['tmp_name'] . "end;";
$imagePath = '';
$thumbnailPath = '';
// echo "before";
// if a file is given
if (trim($image['tmp_name']) != '') {
$ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];
// generate a random new file name to avoid name conflict
$imagePath = md5(rand() * time()) . ".$ext";
list($width, $height, $type, $attr) = getimagesize($image['tmp_name']);
// make sure the image width does not exceed the
// maximum allowed width
if ($width > $image_width) {
// echo "after";
$result = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, $image_width);
$imagePath = $result;
} else {
$result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
}
if ($result) {
// create thumbnail
$thumbnailPath = md5(rand() * time()) . ".$ext";
$result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, $thumbnail_width);
// create thumbnail failed, delete the image
if (!$result) {
unlink($uploadDir . $imagePath);
$imagePath = $thumbnailPath = '';
} else {
$thumbnailPath = $result;
}
} else {
// the product cannot be upload / resized
$imagePath = $thumbnailPath = '';
}
}
return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);
}
(Front-end):
Future<bool> uploadFile(File imageFile, String id) async {
var stream = http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse(path_api + 'patients/insertImage.php');
print(uri.path);
var request = http.MultipartRequest('POST', uri);
var multiPartFile = http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
request.fields['id'] = id;
request.files.add(multiPartFile);
var response = await request.send();
if (response.statusCode == 200) {
print('ok');
} else {
print('nope');
}
}
Future getImageCamera() async {
var image = await picker.pickImage(source: ImageSource.camera);
setState(
() {
if (image != null) {
_image = File(image.path);
} else {
print('no image selected');
}
},
);
}

How do I modify this to upload multiple files?

My upload code is this. I submit the image to it with postdata. I want to make the file select box accept multiple picutes, and have it work on the backend. I can get the header location to work just fine on my own, but using an array of files has proved to be difficult, even though I've spent hours on stack overflow and google. I'd love it if somebody could show me how to do it.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$browse = $_POST["browse"];
preg_match('/\.([a-zA-Z]+?)$/', $_FILES['userfile']['name'], $matches);
if(in_array(strtolower($matches[1]), $accepted)) {
if($_FILES['userfile']['size'] <= $maxsize) {
$newname = md5_file($_FILES['userfile']['tmp_name']).'.'.$matches[1];
$browse = $_POST["browse"];
if ($browse == "1") {
$filedir = 'img';
} else if ($browse == "2") {
$filedir = 'zega';
} else if ($browse == "3") {
$filedir = 'noimg';
} else if ($browse == "4") {
$filedir = 'adult';
} else if ($browse == "5") {
$filedir = 'temp';
} else {
$filedir = 'noimg';
}
move_uploaded_file($_FILES['userfile']['tmp_name'], $filedir.'/'.$newname);
$path = $filedir.'/'.$newname;
if (strpos($path,'jpg') !== false){
$img = imagecreatefromjpeg ($path);
imagejpeg ($img, $path, 100);
imagedestroy ($img);
} else if (strpos($path,'gif') !== false){
$img = imagecreatefromgif ($path);
imagegif ($img, $path, 100);
imagedestroy ($img);
} else if (strpos($path,'bmp') !== false){
$img = imagecreatefrombmp ($path);
imagebmp ($img, $path, 100);
imagedestroy ($img);
}
header("Location: index.php?p=uploaded&img=$newname");
} else
header("Location: index.php?p=error&num=2");
} else
header("Location: index.php?p=error&num=1");
}
?>
foreach($_FILES as $key_file=>$file_info){
//your code here instead $_FILES['userfile']['tmp_name'] use $file_info['tmp_name']
}
i wrote a class for uploads sometimes ago.
this class has ability to upload mutiple files at the same time(such as picture .etc).
it also has other ability such as :
-if you upload mutiple files with the same name it will automatically change their name
-you can add permitted types
-set maximum size of uploaded files
...
class Upload {
protected $_uploaded = array();
protected $_destination_upload_folder;
//Constraint
protected $_max_upload_size = 512000;
protected $_permitted_files = array('image/gif', 'image/png', 'image/jpg', 'image/jpeg', 'image/pjpeg');
protected $_error_messages = array();
protected $_renamed_file = false;
public function __construct($input_upload_path) {
if(!is_dir($input_upload_path) || !is_writable($input_upload_path)){
throw new Exception("$input_upload_path must be a valid,writable path!");
}
$this->_destination_upload_folder = $input_upload_path;
$this->_uploaded = $_FILES;
}
protected function checkError($fileName, $error){
switch ($error) {
case 0:
return true;
case 1:
case 2:
$this->_error_messages[] = "$fileName exceeds maximum file size : "
.$this->getMaxSize();
return true;
case 3:
$this->_error_messages[] = "Error while uploading $fileName.please try again.";
return false;
case 4:
$this->_error_messages[] = "No file selected.";
return false;
default:
$this->_error_messages[] = "System Error uploading $fileName.Please contact administrator.";
return false;
return false;
}
}
protected function checkSize($fileName, $size){
if($size == 0){
return false;
}else if($size > $this->_max_upload_size){
$this->_error_messages[] = "$fileName exceeds maximum size : ".
$this->_max_upload_size;
return false;
}else{
return true;
}
}
protected function checkType($fileName, $type){
if(!in_array($type, $this->_permitted_files)){
$this->_error_messages[] = 'This type of file is not allowed for uploading '
.'.please upload permitted files.';
return false;
}else{
return true;
}
}
public function checkName($input_file_name, $overwrite)
{
$input_file_name_without_spaces = str_replace(' ', '_', $input_file_name);
if($input_file_name_without_spaces != $input_file_name){
$this->_renamed_file = true;
}
if(!$overwrite){
$all_files_in_upload_directory = scandir($this->_destination_upload_folder);
if(in_array($input_file_name_without_spaces, $all_files_in_upload_directory)){
$dot_position = strrpos($input_file_name_without_spaces, '.');
if($dot_position){
$base = substr($input_file_name_without_spaces, 0, $dot_position);
$extension = substr($input_file_name_without_spaces, $dot_position);
}else{
$base = substr($input_file_name_without_spaces);
$extension = '';
}
$i = 1;
do{
$input_file_name_without_spaces = $base.'_'.$i++.$extension;
}while(in_array($input_file_name_without_spaces, $all_files_in_upload_directory));
$this->_renamed_file = true;
}
}
return $input_file_name_without_spaces;
}
protected function getMaxSize(){
return number_format(($this->_max_upload_size)/1024, 1).'kb';
}
protected function isValidMime($types)
{
$also_valid_mimes = array('application/pdf', 'text/plain', 'text/rtf');
$all_valid_mimes = array_merge($this->_permitted_files, $also_valid_mimes);
foreach($types as $type){
if(!in_array($type, $all_valid_mimes)){
throw new Exception("$type is not a valid permitted mime type!");
}
}
}
public function addPermittedType($input_type_name)
{
$input_type_name_array = (array)$input_type_name;
$this->isValidMime($input_type_name_array);
$this->_permitted_files = array_merge($this->_permitted_files, $input_type_name_array);
}
protected function processFile($fileName, $error, $size, $type, $tmp_name, $overwrite)
{
$check_upload_error = $this->checkError($fileName, $error);
if($check_upload_error){
$check_uploaded_file_type = $this->checkType($fileName, $type);
$check_uploaded_file_size = $this->checkSize($fileName, $size);
if($check_uploaded_file_type && $check_uploaded_file_size){
$new_uploaded_file_name = $this->checkName($fileName, $overwrite);
$upload_result = move_uploaded_file($tmp_name, $this->_destination_upload_folder.$new_uploaded_file_name);
if($upload_result){
$messages = $new_uploaded_file_name.' uploaded successfully! <br >';
if($this->_renamed_file){
$messages .= ' and renamed successfully!';
}
$this->_error_messages[] = $messages;
} else {
$this->_error_messages[] = 'Could`nt upload '.$fileName;
}
}
}
}
public function move($overwrite = FALSE){
$file = current($this->_uploaded);
if(is_array($file['name'])){
foreach($file['name'] as $index => $filename){
$this->_renamed_file = false;
$this->processFile($filename, $file['error'][$index],
$file['size'][$index], $file['type'][$index], $file['tmp_name'][$index], $overwrite);
}
}else{
$this->processFile($file['filename'], $file['error'], $file['size'], $file['type']
, $file['tmp_name'], $overwrite);
}
}
public function getErrorMessages(){
return $this->_error_messages;
}
public function setMaxSize($new_upload_size)
{
if(!is_numeric($new_upload_size) || $new_upload_size <= 0){
throw new Exception("new maximum upload size must a number!");
}
$this->_max_upload_size = (int)$new_upload_size;
}
}
$max_upload_size = 1024 * 1024;
if(isset($_POST['upload_button'])){
$destination_upload_folder = 'destination of upload folder here....';
require_once 'Upload class filename...';
try{
$upload = new Upload($destination_upload_folder);
$upload->setMaxSize($max_upload_size);
$upload->addPermittedType('application/pdf');
$upload->move(true);
$result = $upload->getErrorMessages();
}catch(Exception $e){
echo $e->getMessage();
}
}

Upload image with resize in php

I have a problem with image uploading in php
I want uploading with resizing image to width=600px
ex, when I uploaded an image with width of 2000px it should be uploaded with width of 600px
and of course smaller size on disk...
php file is:
<?php
require_once("db.php");
$name = trim($_POST['name']);
$addr = trim($_POST['addr']);
$dist = trim($_POST['dist']);
$city = trim($_POST['city']);
$phone = trim($_POST['phone']);
$price = trim($_POST['price']);
$lati = trim($_POST['lati']);
$long = trim($_POST['long']);
$tid = trim($_POST['type']);
$img = "";
if($_FILES)
{
//var_dump($_FILES);
$random_str = md5(uniqid(mt_rand(), true));
$f_name = "tmp/".$random_str.".jpg";
move_uploaded_file($_FILES['placeimg']['tmp_name'], $f_name);
$img = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/".$f_name;
$uploadedfile = $_FILES['placeimg']['tmp_name'];
$size=filesize($_FILES['placeimg']['tmp_name']);
$uploadedfile =$_FILES['placeimg']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($_FILES['placeimg']['tmp_name']);
$newwidth=600;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
//$filename = "tmp/". $_FILES['file']['name'];
imagejpeg($tmp,$uploadedfile,75);
imagedestroy($src);
}
$sql = "INSERT INTO `Place`(`PName`, `PAddr`, `PDistrict`, `PCity`, `PImage`, `PPhone`, `PPrice`, `PLat`, `PLong`, `TID`, `PStatus`) VALUES ('{$name}', '{$addr}', '{$dist}', '{$city}', '{$img}', '{$phone}', '{$price}', '{$lati}', '{$long}', '{$tid}', '0')";
$status = 0;
$mess = "Err!";
if(mysql_query($sql))
{
$status = 1;
$mess = "Successful! Waiting approve";
}
$json['status'] = $status;
$json['message'] = $mess;
echo json_encode($json);
?>
the result is a big image without resizing
can you help?
try this:
function upload_resize($file,$newwidth,$resolution,$location,$prefix){
define ("MAX_SIZE","2048");
error_reporting(0);
$image =$file["name"];
$uploadedfile = $file['tmp_name'];
if ($image) {
$filename = stripslashes($file['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
//Unknown Image extension
return 1;
}
else
{
$size=filesize($file['tmp_name']);
if ($size > MAX_SIZE*1024){
//You have exceeded the size limit
return 2;
}
if($extension=="jpg" || $extension=="jpeg" ) {
$uploadedfile = $file['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension=="png") {
$uploadedfile = $file['tmp_name'];
$src = imagecreatefrompng($uploadedfile);
}
else {
$src = imagecreatefromgif($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = $location.$prefix.$file['name'];
imagejpeg($tmp,$filename,$resolution);
imagedestroy($src);
imagedestroy($tmp);
}
}
return 0;
}
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// get file from user and send to this function:
$res=upload_resize($_FILES["image"],600,100,'../images','');
switch ($res){
case 0 : echo 'images saved'; break;
case 1 : echo 'Unknown file type'; break;
case 2 : echo 'file size error'; break;
}
i use this function for upload and resize image.
// for outputting a jpeg image, Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');
// Output the image
imagejpeg($tmp,$uploadedfile,75);
try this..
You create a new pattern file (using imagecreatetruecolor), but u didn't use a original picture.
Try use imagecopyresampled
like this:
<?php
require_once("db.php");
$name = trim($_POST['name']);
$addr = trim($_POST['addr']);
$dist = trim($_POST['dist']);
$city = trim($_POST['city']);
$phone = trim($_POST['phone']);
$price = trim($_POST['price']);
$lati = trim($_POST['lati']);
$long = trim($_POST['long']);
$tid = trim($_POST['type']);
$img = "";
if($_FILES)
{
//var_dump($_FILES);
$random_str = md5(uniqid(mt_rand(), true));
$f_name = "tmp/".$random_str.".jpg";
move_uploaded_file($_FILES['placeimg']['tmp_name'], $f_name);
$img = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/".$f_name;
$uploadedfile = $_FILES['placeimg']['tmp_name'];
$size=filesize($_FILES['placeimg']['tmp_name']);
$uploadedfile =$_FILES['placeimg']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($_FILES['placeimg']['tmp_name']);
$newwidth=600;
$newheight=($height/$width)*$newwidth;
$tmp=imagecreatetruecolor($newwidth,$newheight);
$buff = imagecreatefromjpeg($uploadedfile);
imagecopyresampled($tmp, $b, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//$filename = "tmp/". $_FILES['file']['name'];
imagejpeg($tmp,$uploadedfile,75);
imagedestroy($src);
}
$sql = "INSERT INTO `Place`(`PName`, `PAddr`, `PDistrict`, `PCity`, `PImage`, `PPhone`, `PPrice`, `PLat`, `PLong`, `TID`, `PStatus`) VALUES ('{$name}', '{$addr}', '{$dist}', '{$city}', '{$img}', '{$phone}', '{$price}', '{$lati}', '{$long}', '{$tid}', '0')";
$status = 0;
$mess = "Err!";
if(mysql_query($sql))
{
$status = 1;
$mess = "Successful! Waiting approve";
}
$json['status'] = $status;
$json['message'] = $mess;
echo json_encode($json);
?>

Issues with PHP image upload

I've been creating a HTML5 Drag & Drop image up-loader. All is good with the Javascript side of things however the PHP is driving me crazy!
I've been able to create a script that successfully places a image in a folder upon the drop of an image, however once it tries to create a thumb nail for the image and place the image link into the users db table it all goes to pot. I've sat here for hours on end, trying and trying to no avail, so i believe as it is now just about 3am GMT i should admit defeat and ask for a little help.
The JavaScript:
$(function(){
var dropbox = $('#dropbox'),
message = $('.message', dropbox);
dropbox.filedrop({
paramname:'pic',
maxfiles: 5,
maxfilesize: 200,
url: 'uploadCore.php',
uploadFinished:function(i,file,response){
$.data(file).addClass('done');
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files!');
break;
case 'FileTooLarge':
alert(file.name+' is too large! Please upload files up to 200mb.');
break;
default:
break;
}
},
beforeEach: function(file){
if(!file.type.match(/^image\//)){
alert('Only images are allowed!');
return false;
}
},
uploadStarted:function(i, file, len){
createImage(file);
},
progressUpdated: function(i, file, progress) {
$.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">'+
'<span class="imageHolder">'+
'<img />'+
'<span class="uploaded"></span>'+
'</span>'+
'<div class="progressHolder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
function createImage(file){
var preview = $(template),
image = $('img', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function(e){
image.attr('src',e.target.result);
};
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
$.data(file,preview);
}
function showMessage(msg){
message.html(msg);
}
});
Now for the PHP:
<?php
// db connection
include("db-info.php");
$link = mysql_connect($server, $user, $pass);
if(!mysql_select_db($database)) die(mysql_error());
include("loadsettings.inc.php");
//$upload_dir = 'pictures/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
if (isset($_SESSION["imagehost-user"]))
{
$session = true;
$username = $_SESSION["imagehost-user"];
$password = $_SESSION["imagehost-pass"];
$q = "SELECT id FROM `members` WHERE (username = '$username') and (password = '$password')";
if(!($result_set = mysql_query($q))) die(mysql_error());
$number = mysql_num_rows($result_set);
if (!$number) {
session_destroy();
$session = false;
}else {
$row = mysql_fetch_row($result_set);
$loggedId = $row[0];
}
}
$date = date("d-m-y");
$lastaccess = date("y-m-d");
$ip = $_SERVER['REMOTE_ADDR'];
$type = "public";
$pic = $_FILES['pic'];
$n = $pic;
$rndName = md5($n . date("d-m-y") . time()) . "." . get_extension($pic['name']);
$upload_dir = "pictures/" . $rndName;
move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name']);
// issues starts here
$imagePath = $upload_dir;
$img = imagecreatefromunknown($imagePath);
$mainWidth = imagesx($img);
$mainHeight = imagesy($img);
$a = ($mainWidth >= $mainHeight) ? $mainWidth : $mainHeight;
$div = $a / 150;
$thumbWidth = intval($mainWidth / $div);
$thumbHeight = intval($mainHeight / $div);
$myThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($myThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainWidth, $mainHeight);
$thumbPath = "thumbnails/" . basename($imagePath);
imagejpeg($myThumb, $thumbPath);
$details = intval(filesize($imagePath) / 1024) . " kb (" . $mainWidth . " x " . $mainHeight . ")" ;
$id = md5($thumbPath . date("d-m-y") . time());
$q = "INSERT INTO `images`(id, userid, image, thumb, tags, details, date, access, type, ip)
VALUES('$id', '$loggedId', '$imagePath', '$thumbPath', '$tags', '$details', '$date', '$lastaccess', 'member-{$type}', '$ip')";
if(!($result_set = mysql_query($q))) die(mysql_error());*/
exit_status('File was uploaded successfuly!');
// to here
$result = mysql_query("SELECT id FROM `blockedip` WHERE ip = '$ip'");
$number = mysql_num_rows($result);
if ($number) die(""); // blocked IP message
function imagecreatefromunknown($path) {
$exten = get_extension($path);
switch ($exten) {
case "jpg":
$img = imagecreatefromjpeg($path);
break;
case "gif":
$img = imagecreatefromgif($path);
break;
case "png":
$img = imagecreatefrompng($path);
break;
}
return $img;
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
It seems you pass wrong path to the imagecreatefromunknown() function. You pass $imagePath that equals $upload_dir, but your image destination is $upload_dir.$pic['name']

Display die('message') problem

How do i display the die() message in if($allowed) at the same place as move_uploaded_file result?
<?php
$destination_path = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
$allowed[] = 'image/gif';
$allowed[] = 'image/jpeg';
$allowed[] = 'image/pjpeg';
$allowed[] = 'image/png';
if (!in_array($_FILES['myfile']['type'], $allowed)) {
die('Wrong file type!');
}
$result = 0;
$now = time();
$ext = end(explode(".", $_FILES['myfile']["name"]));
$filename = ( $_FILES['myfile'][0].$now.".".$ext);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $destination_path .$filename)) {
$result = 1;
}
sleep(1);
?>
<script language="javascript" type="text/javascript"> window.top.window.stopUpload('<? php echo $result; ?>', '<?php echo $filename; ?>');</script>
Javascript to display move_uploaded_file result:
function stopUpload(success,filename){
var result = '';
if (success == 1){
result = '<span class="msg">Great!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">Not so great.<\/span><br/><br/>';
}
do you mean in the same condition?
if (in_array($_FILES['myfile']['type'], $allowed) && #move_uploaded_file($_FILES['myfile']['tmp_name'], $destination_path .$filename)) {
$result = 1;
} else {
die("Error while uploding file");
}
Add a third $result condition (-1, for example), then instead of die(message);, do $result = -1; exit(0);. Change the JavaScript so else if (success == -1) { result = 'Wrong file type!' }

Categories