I have this Smart Webview I got on https://github.com/ which was great. Being Android newbie developer, I have been having issue trying to solve this problem. If I select image from the phone directory and send to the backend(PHP); everything worked fine: image is moved to the upload folder; but If I take picture using the Android camera, the image never send to folder but the name of the image is saves into the database.
MainActivity for image upload
// handling input[type="file"]
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams){
if(check_permission(2) && check_permission(3)) {
if (ASWP_FUPLOAD) {
asw_file_path = filePathCallback;
Intent takePictureIntent = null;
Intent takeVideoIntent = null;
if (ASWP_CAMUPLOAD) {
boolean includeVideo = false;
boolean includePhoto = false;
// Check the accept parameter to determine which intent(s) to include.
paramCheck:
for (String acceptTypes : fileChooserParams.getAcceptTypes()) {
// Although it's an array, it still seems to be the whole value.
// Split it out into chunks so that we can detect multiple values.
String[] splitTypes = acceptTypes.split(", ?+");
for (String acceptType : splitTypes) {
switch (acceptType) {
case "*/*":
includePhoto = true;
includeVideo = true;
break paramCheck;
case "image/*":
includePhoto = true;
break;
case "video/*":
includeVideo = true;
break;
}
}
}
// If no `accept` parameter was specified, allow both photo and video.
if (fileChooserParams.getAcceptTypes().length == 0) {
includePhoto = true;
includeVideo = true;
}
if (includePhoto) {
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = create_image();
takePictureIntent.putExtra("PhotoPath", asw_pcam_message);
} catch (IOException ex) {
Log.e(TAG, "Image file creation failed", ex);
}
if (photoFile != null) {
asw_pcam_message = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
}
if (includeVideo) {
takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
File videoFile = null;
try {
videoFile = create_video();
} catch (IOException ex) {
Log.e(TAG, "Video file creation failed", ex);
}
if (videoFile != null) {
asw_vcam_message = "file:" + videoFile.getAbsolutePath();
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(videoFile));
} else {
takeVideoIntent = null;
}
}
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
if (!ASWP_ONLYCAM) {
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType(ASWV_F_TYPE);
if (ASWP_MULFILE) {
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
}
Intent[] intentArray;
if (takePictureIntent != null && takeVideoIntent != null) {
intentArray = new Intent[]{takePictureIntent, takeVideoIntent};
} else if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else if (takeVideoIntent != null) {
intentArray = new Intent[]{takeVideoIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.fl_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, asw_file_req);
}
return true;
}else{
get_file();
return false;
}
}
//Creating image file for upload
private File create_image() throws IOException {
#SuppressLint("SimpleDateFormat")
String file_name = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
String new_name = "file_"+file_name+"_";
File sd_directory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(new_name, ".jpg", sd_directory);
}
//Creating video file for upload
private File create_video() throws IOException {
#SuppressLint("SimpleDateFormat")
String file_name = new SimpleDateFormat("yyyy_mm_ss").format(new Date());
String new_name = "file_"+file_name+"_";
File sd_directory = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
return File.createTempFile(new_name, ".3gp", sd_directory);
}
PHP that handles upload
if(isset($_FILES['photo'])){
$upload_dir = 'profile_img/'; // upload directory
$email = $_POST['email'];
$imgFile = $_FILES['photo']['name'];
$tmp_dir = $_FILES['photo']['tmp_name'];
$imgSize = $_FILES['photo']['size'];
$imgType = $_FILES['photo']['type'];
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png'); // image extensions
$vid_extensions = array('avi', 'mp4', 'wav','3gp','AAC','flv','wmv'); // video extensions
$aud_extensions = array('mp3'); // audio extensions
// rename uploading image
$userpic = rand(1000,1000000).".".$imgExt;
if(!empty($imgFile)){
$pic = $userpic;
}else{
$pic = '';
}
if(!empty($imgFile) && in_array($imgExt, $valid_extensions)){
move_uploaded_file($tmp_dir,$upload_dir.$pic);
}
if(!empty($imgFile) && in_array($imgExt, $vid_extensions)){
move_uploaded_file($tmp_dir,$video.$pic);
}
if(!empty($imgFile) && in_array($imgExt, $aud_extensions)){
move_uploaded_file($tmp_dir,$audio.$pic);
}
$query = mysqli_query($mysqli,"UPDATE customer_login SET img = '$pic' WHERE email='$email'");
if($query){
echo 1;
}else{
echo "Error occured: ".$mysqli->error;
}
}
Uri.fromFile(photoFile))
Since Android N/7 you cannot use a file uri.
It will produce a FileUriExposedException.
Use FileProvider.getUriForFile() instead to obtain a content scheme uri.
Related
I am working on a project and so I am writing Object Oriented PHP. Hence, I have created a class called FileUploader. This class has all the method to validate file size, and file extension type as well as create directories if not existing.
Everything works just fine but I noticed that it only creates empty directories and does not move the uploaded files. I tried accessing the File error form the stored property but it always gives 0 as the error code
This is the FileUploader class
<?php
namespace Utility\Classes;
class FileUploader
{
//property declarations
protected $error_msg = array();
protected $tmp_file_name;
protected $max_file_size;
protected $target_location;
protected $allowed_file_type = array();
protected $File;
protected $default_file_name = true;
private $backlink_step;
private $unit_size; //to keep track of measurement unit of upload sizes MB|KB|BYTES
function __construct(array $file, array $allowed_ext = [], int $file_max_size = 5)
{
$this->File = $file;
$this->backlink_step = '';
$this->set_allowed_extensions($allowed_ext);
$this->set_max_upload_size($file_max_size);
}
/*This method helps to make sure that files are uploaded to the exact location as desired
*as in the case of deep nesting of subdirectory process
*/
function set_backlink_step($prfx)
{
$this->backlink_step = $prfx;
}
function set_target(string $target, $dated = false)
{
$this->target_location = $target;
if ($dated) {
$this->target_location .= "/" . $date = date("M-Y");
}
}
function get_target()
{
return $this->target_location;
}
//method to set valid/allowed file types
function set_allowed_extensions(array $allowed_ext)
{
$this->allowed_file_type = $allowed_ext;
}
//method to get the allowed file extensions
function get_allowed_extensions()
{
return $this->allowed_file_type;
}
function set_error_msg($err)
{
$this->error_msg[] = $err;
}
function get_error_msg()
{
return $this->error_msg;
}
function set_file_name($name)
{
$this->File['name'] = $name;
}
function get_file_name()
{
return $this->File['name'];
}
function get_tmp_name()
{
return $this->File['tmp_name'];
}
/**
* #description: method to return file size in a specified unit
* #param:String ['TB'|'MB'|'KB'|'B'] default MB
* #return: Int file size
* */
function get_file_size(String $unit = "MB")
{
if (strtolower($unit) === "tb") {
$quadrant = 1024 * 1024 * 1024;
} elseif (strtolower($unit) === "mb") {
$quadrant = 1024 * 1024;
} elseif (strtolower($unit) === "kb") {
$quadrant = 1024;
} elseif (strtolower($unit) === "b") {
$quadrant = 1;
}
$size = $this->file_size() / $quadrant;
return number_format($size, 2);
}
/**
* #return int size of the file
* */
function file_size()
{
$fsize = $this->File['size'];
return $fsize;
}
/* Method to get the extension name of a file eg: jpg,mp4 */
function get_ext()
{
$extension = explode('.', $this->get_file_name());
return "." . end($extension);
}
function validate($allowed_ext = [])
{
//fall back to the object allowed_file_type property if param not set by user
if (empty($allowed_ext)) {
$allowed_ext = $this->get_allowed_extensions();
}
//validate allowed file type if specified in the array
if (!empty($allowed_ext)) {
if (!$this->is_allowed_extension($allowed_ext)) {
$this->set_error_msg("Type of '{$this->get_file_name()} does not match allowed file types [" . implode('|', $this->get_allowed_extensions()) . "]");
return false;
}
}
//validate file size
if ($this->is_above_max_upload_size()) {
$this->set_error_msg("Size of the file '{$this->get_file_name()}' is larger than max allowed size of {$this->get_max_upload_size()}");
return false;
}
return true;
}
/*Method to upload file
* #return: the uploaded target location
*/
function upload_file()
{
//create necessary directories if not in existence
$this->create_dir();
$target = $this->backlink_step . $this->target_location . "/" . $this->get_file_name();
//attempt upload of the file
if (move_uploaded_file($this->tmp_file_name, $target)) {
//update target location with the filename
return $target;
} else {
//return false;
die("tmp_name: {$this->get_tmp_name()} \n target: {$target} \n Error: {$this->File['error']}");
}
}
/*This method sets the maximum upload size for file track and album_art respectively
*This method ignores invalid value for unit and replaces it with bytes*/
function set_max_upload_size($file_size, $unit = "MB")
{
$mulitplicant = 1;
if (strtolower($unit) === "tb") {
$multiplicant = 1024 * 1024 * 1024;
} elseif (strtolower($unit) === "mb") {
$multiplicant = 1024 * 1024;
} elseif (strtolower($unit) === "kb") {
$multiplicant = 1024;
} else {
$unit = "Bytes";
}
$this->max_file_size = $multiplicant * $file_size; //set max size for file
$this->unit_size = strtoupper($unit);
}
function get_max_upload_size()
{
return $this->max_file_size;
}
/*Method to compare the size of files to be uploaded with the maximum allowed size*/
function is_above_max_upload_size()
{
$file_unit = $this->unit_size;
//return FALSE if upload size > max size otherwise TRUE
return ($this->file_size() > $this->get_max_upload_size()) ? true : false;
}
/*Method to check if upload file is allowed in by extension name
*The first paramater takes the string of the actual file extension
*The second parameter takes an array of allowed extensions
*/
function is_allowed_extension(array $allowed_ext)
{
return (!in_array($this->get_ext(), $allowed_ext)) ? false : true;
}
//method to create directories
function create_dir()
{
//check if user set a storage location and attempt to create the location
if (empty($this->get_target())) {
$this->set_error_msg('Target Not set.');
return false;
}
//Create the directory
$location = explode('/', $this->get_target());
$prepend = $this->backlink_step . "";
foreach ($location as $key => $value) {
if (!is_dir($prepend . $value)) {
mkdir($prepend . $value);
}
$prepend .= $value . "/";
}
}
}
Then I have another php script where I process the uploaded file by instantiating the FileUploader Class with the $_FILES variable process.php
require_once "../vendor/autoload.php";
use Utility\Classes\FileUploader;
//Instantiate new FileUploader with the files to be uploaded.
$LogoUploader = new FileUploader($_FILES['logo'], ['.png', '.jpg']);
//validate logo size and type - Upload to folder if everything Ok
$logo_validated = $LogoUploader->validate();
//upload files that passed validation
if ($logo_validated) {
$LogoUploader->set_target($location);
$LogoUploader->set_backlink_step('../');
$ltarget = $LogoUploader->upload_file();
if (!$ltarget) {
//upload error
print_error($LogoUploader->get_error_msg());
exit;
} else { //upload success
print "Logo uploaded successfully";
}
} else { //validation error
print_error($LogoUploader->get_error_msg());
exit;
}
Please what am I not doing right?? everything is ok, validation is working, user can set the upload target and if it does not exist, it will be created but it does not upload the file into the created directory or anywhere else in my working directory
I think you need to change the following line
if (move_uploaded_file($this->tmp_file_name, $target)) {
to
if (move_uploaded_file( $this->get_tmp_name(), $target )) {
in the upload_file method. ie:
public function upload_file(){
$this->create_dir();
$target = $this->backlink_step . $this->target_location . "/" . $this->get_file_name();
if (move_uploaded_file( $this->get_tmp_name(), $target )) {
return $target;
} else {
die("tmp_name: {$this->get_tmp_name()} \n target: {$target} \n Error: {$this->File['error']}");
}
}
Problem
I am trying to send push notification through PHP, to both Android and iOS, but I have lots of devices to send the notification, and you can see the code that it sends the notification to all of them in a loop. It's really not optimized as my dashboard gets stuck for more than a minute due to the running loop, also somehow it is not even sending a notification to all active accounts.
Can anyone here help me out?
Code
public function insert()
{
// Set the validation rules
$this->form_validation->set_rules('title', 'Title', 'required|trim');
// If the validation worked
if ($this->form_validation->run())
{
$get_post = $this->input->get_post(null,true);
$get_post['tags'] = is_array($this->input->get_post('tags')) ? $this->input->get_post('tags') : [];
if(count($get_post['tags']) == 0)
{
$_SESSION['msg_error'][] = "Tags is a required field";
redirect('admin/newsfeed/insert');
exit;
}
# File uploading configuration
$upload_path = './uploads/newsfeeds/';
$config['upload_path'] = $upload_path;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
$image = '';
# Try to upload file now
if ($this->upload->do_upload('image'))
{
# Get uploading detail here
$upload_detail = $this->upload->data();
$image = $upload_detail['file_name'];
} else {
$uploaded_file_array = (isset($_FILES['image']) and $_FILES['image']['size'] > 0 and $_FILES['image']['error'] == 0) ? $_FILES['image'] : '';
# Show uploading error only when the file uploading attempt exist.
if( is_array($uploaded_file_array) )
{
$uploading_error = $this->upload->display_errors();
$_SESSION['msg_error'][] = $uploading_error;
}
}
# File uploading configuration
$upload_path = './uploads/newsfeeds/';
$config['upload_path'] = $upload_path;
$config['allowed_types'] = '*';
$config['encrypt_name'] = true;
$config['max_size'] = 51200; //KB
$this->upload->initialize($config);
$audio = '';
# Try to upload file now
if ($this->upload->do_upload('audio'))
{
# Get uploading detail here
$upload_detail = $this->upload->data();
$audio = $upload_detail['file_name'];
}
else
{
$uploaded_file_array = (isset($_FILES['audio']) and $_FILES['audio']['size'] > 0 and $_FILES['audio']['error'] == 0) ? $_FILES['audio'] : '';
# Show uploading error only when the file uploading attempt exist.
if( is_array($uploaded_file_array) )
{
$uploading_error = $this->upload->display_errors();
$_SESSION['msg_error'][] = $uploading_error;
}
}
$get_post['image'] = $image;
$get_post['audio'] = $audio;
if($id = $this->newsfeed_model->insert($get_post))
{
if($get_post['status'])
{
// send push notification to all users
$notification = $this->newsfeed_model->get_newsfeed_by_id($id);
$notification->notification_type = 'article';
$notification->title = $get_post['n_title'];
$notification->body = $get_post['n_description'];
$query = $this->db->get_where('users', ['device_id !=' => '']);
foreach ($query->result() as $row) {
if ($row->device == 'IOS') {
$this->notification_model->sendPushNotificationIOS($row->device_id, $notification);
}
if ($row->device == 'ANDROID') {
$this->notification_model->sendPushNotificationAndroid($row->device_id, $notification);
}
}
}
$_SESSION['msg_success'][] = 'Record added successfully...';
if($image){
redirect('admin/newsfeed/crop_image?id='.$id);
} else {
redirect('admin/newsfeed/');
}
}
}
$this->data['selected_page'] = 'newsfeed';
$this->load->view('admin/newsfeed_add', $this->data);
}
Description
The method is adding a newsfeed, its checks for the validations, then it inserts the feed to the db, once thats done, it sends out the notification to all devices.
Problematic Chunk
if($id = $this->newsfeed_model->insert($get_post))
{
if($get_post['status'])
{
// send push notification to all users
$notification = $this->newsfeed_model->get_newsfeed_by_id($id);
$notification->notification_type = 'article';
$notification->title = $get_post['n_title'];
$notification->body = $get_post['n_description'];
$query = $this->db->get_where('users', ['device_id !=' => '']);
foreach ($query->result() as $row) {
if ($row->device == 'IOS') {
$this->notification_model->sendPushNotificationIOS($row->device_id, $notification);
}
if ($row->device == 'ANDROID') {
$this->notification_model->sendPushNotificationAndroid($row->device_id, $notification);
}
}
}
$_SESSION['msg_success'][] = 'Record added successfully...';
if($image) {
redirect('admin/newsfeed/crop_image?id='.$id);
} else{
redirect('admin/newsfeed/');
}
}
Thank you in advance.
Hi im creating a project in laravel 4.2 that uploads different files (e.g Pdf and images) in specific folders about 8 or 9 folders to be exact i just try the do a if statement but dont know what happend but its not working and there are no error displayed when i execute the code. please help me work this code or do you have any idea to simplify my code TIA!
Here's my code in my controller
public function upload()
{
$finame = Input::get('name');
$ftype = Input::get('type');
$username = Input::get('user');
$desc = Input::get('desc');
$date = Input::get('date');
$upload = Input::file('file');
$add = Files::upload2($finame,$ftype,$username,$desc,$date,$upload);
if ($add == true && $ftype == "pf") {
$upload -> move(public_path('pf'),$upload->getClientOriginalName());
return \Response::json(array('success' => true));
return Redirect::to('/home')->with('message', 'message|Record Successfully Added.');
} elseif ($add == true && $ftype == "sf") {
$upload -> move(public_path('sf'),$upload->getClientOriginalName());
return \Response::json(array('success' => true));
return Redirect::to('/home')->with('message', 'message|Record Successfully Added.');
} } elseif ($add == true && $ftype == "gale") {
$upload -> move(public_path('gale'),$upload->getClientOriginalName());
return \Response::json(array('success' => true));
return Redirect::to('/home')->with('message', 'message|Record Successfully Added.');
} } elseif ($add == true && $ftype == "advisory") {
$upload -> move(public_path('advisory'),$upload->getClientOriginalName());
return \Response::json(array('success' => true));
return Redirect::to('/home')->with('message', 'message|Record Successfully Added.');
} else {
return Redirect::back()->with('message', 'error|Error');
}
}
And my code in model:
public static function upload2($finame,$ftype,$username,$desc,$date,$upload)
{
$files = new self;
$files->file_name = $finame;
$files->file_type = $ftype;
$files->username = $username;
$files->description = $desc;
$files->date = $date;
$files->upload = $upload->getClientOriginalName();
try {
$files->save();
} catch (Exception $e) {
dd($e);
}
}
and in the view add this script:
<script>
var form = document.getElementById('upload');
var request = new XMLHttpRequest();
form.addEventListener('submit', function(e){
e.preventDefault();
var formdata = new FormData(form);
request.open('post', '/upload');
request.addEventListener("load", transferComplete);
request.send(formdata);
});
function transferComplete(data){
response = JSON.parse(data.currentTarget.response);
if(response.success){
document.getElementById('message').innerHTML = "File Successfully Uploaded!";
}
}
</script>
In my php file using file uploading control. After unlink previous file and update with new file it's not getting update with new image file. It's showing previous image in listing, when i refresh it's showing new image. Using both listing and update screen in single php file. I used the document cache clear. Even it's not working.
<?php
require_once("../config/config.php");
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
<?php
require_once("../images.inc.php");
if(Tools::isLoggedIn('admin') == false)
{
Tools::redirectTo($link->rewrite_link(array("template"=>ADMIN_URI."index")));
}
$id_product = (Tools::getVar("id_product")) ? Tools::getVar("id_rpoduct") : 0;
$page = intval(Tools::getVar("page"));
$product = new Product($id_product);
if(Tools::isSubmit("OnSave"))
{
$id_product = Tools::getVar("id_product");
$product = new Product($id_product);
$product->name = Tools::getVar("name");
$product->id_category = Tools::getVar("id_category");
$product->short_description = Tools::getVar("short_description");
$product->code = Tools::getVar("code");
$product->weight = Tools::getVar("weight");
$product->price = Tools::getVar("price");
$product->size = Tools::getVar("size");
$product->meta_title = Tools::getVar("meta_title");
$product->meta_description = Tools::getVar("meta_description");
$product->meta_keyword = Tools::getVar("meta_keyword");
$product->status = Tools::getVar("status");
if(($product->name)=="")
{
$errors['err_name'] = "Name is required";
}
if(($product->short_description)=="")
{
$errors['err_short_description'] = "Description is required";
}//edit on
if($product->id_category <= 0)
{
$errors['err_id_category'] ="Parent Category is required";
}
if($product->code == '')
{
$errors['err_code'] ="Product Code is required";
}
if(sizeof($errors) == 0)
{
if($id_product) {
$product->date_upd = date('Y-m-d H:i:s');
if(isset($_FILES) AND sizeof($_FILES) AND $_FILES['image']['name'] != NULL && $id_product) {
$postimage = $product->postImage($id_product);
}
if($product->update())
{
$redirect = array("template"=>ADMIN_URI."product");
$session->set("success","Product Updated Successfully");
Tools::redirectTo($link->rewrite_link($redirect));
}
else {
$errors['fail'] ="Please Try again Later";
}
}
else {
$product->date_add = date('Y-m-d H:i:s');
$product->date_upd = date('Y-m-d H:i:s');
$id_product = $product->add(DB::RETURN_INSERT_ID);
if(isset($_FILES) AND sizeof($_FILES) AND $_FILES['image']['name'] != NULL && $id_product) {
$product->postImage($id_product);
}
if($id_product){
$redirect = array("template"=>ADMIN_URI."product");
$session->set("success","Product Added Successfully");
Tools::redirectTo($link->rewrite_link($redirect));
}
else {
$errors['fail'] ="Please Try again Later";
}
}
}
}
if(Tools::getVar('action') == 'delete' && Tools::getVar('id_product') )
{
$id_product = Tools::getVar('id_product');
$product = new Product($id_product);
if($product->delete()) {
$session->set("success","Product Deleted successfully");
Tools::redirectTo($link->rewrite_link(array("template"=>ADMIN_URI."product")));
}
else {
$errors['fail'] ="Please Try again Later";
}
}
if(Tools::getVar('action') == "status_change" && Tools::getVar('id_product'))
{
$id_product = Tools::getVar('id_product');
$product = new Product($id_product);
$product->status =Tools::getVar("status");
$product->update();
$session->set("success","Status updated successfully");
Tools::redirectTo($link->rewrite_link(array("template"=>ADMIN_URI."product")));
}
require_once("header.php");
?>
My Image upload class like,
<?php
class Product extends ObjectModel
{
protected function uploadImage($id, $name, $dir, $ext = false)
{
if (isset($_FILES[$name]['tmp_name']) AND !empty($_FILES[$name]['tmp_name']))
{
// Delete old image
if (file_exists($dir.$id.'.'.$this->imageType)) {
$imagesTypes = $this->productImageTypes;
foreach ($imagesTypes AS $k => $imageType)
{
if (file_exists($dir.$id.'-'.stripslashes($imageType['name']).'.jpg'))
{
unlink($dir.$id.'-'.stripslashes($imageType['name']).'.jpg');
}
}
unlink($dir.$id.'.'.$this->imageType);
}
// Check image validity
if ($error = checkImage($_FILES[$name], $this->maxImageSize))
$_errors[] = $error;
elseif (!$tmpName = tempnam(TEMP_DIR, 'SST') OR !move_uploaded_file($_FILES[$name]['tmp_name'], $tmpName))
return false;
else
{
$_FILES[$name]['tmp_name'] = $tmpName;
// Copy new image
if (!imageResize($tmpName, $dir.$id.'.'.$this->imageType, NULL, NULL, ($ext ? $ext : $this->imageType)))
$_errors[] = Tools::displayError('An error occurred while uploading image.');
else {
$imagesTypes = $this->productImageTypes;
foreach ($imagesTypes AS $k => $imageType)
imageResize($dir.$id.'.jpg', $dir.$id.'-'.stripslashes($imageType['name']).'.jpg', (int)($imageType['width']), (int)($imageType['height']));
}
if (sizeof($_errors))
return false;
else
{
unlink($tmpName);
return true;
}
return false;
}
}
return true;
}
}
Assuming that your browser is displaying a cached version of the image since your saving new data to the same file name, try appending a query string containing a randomized string or timestamp to the image url when generating the HTML to display it. Something like this:
PHP
$image_tag='<img src="image-file.jpg?t='.timestamp().'" />';
This should make the browser fetch a fresh version of the image instead of using it's cached version.
hi all when Using exif_imagetype() [function.exif-imagetype]: function for checking images if the user hits the submit button without uploading anything the exif function returns an error in the webpage itself. my question is how to get rid of this error. am pasting the error below
Warning: exif_imagetype() [function.exif-imagetype]: Filename cannot be empty in /mounted- storage/home98a/sub009/sc61374-HGPS/sitakalyanam.com/newsita/php4upload.class.php on line 88
<?php
/*
- PHP4 Image upload script
*/
class imageupload
{
//pblic variables
var $path = '';
var $errorStr = '';
var $imgurl = '';
//private variables
var $_errors = array();
var $_params = array();
var $_lang = array();
var $_maxsize = 1048576;
var $_im_status = false;
//public methods
function imageupload ()
{
//require 'photouploadconfig.php';
if($_GET['Choice']=="1")
{
require 'Photouploddir1.php';
}
elseif ($_GET['Choice']=="2")
{
require 'Photouploddir2.php';
}
elseif ($_GET['Choice']=="3")
{
require 'Photouploddir3.php';
}
elseif ($_GET['horoschoice']=="1")
{
require 'horosuploaddir.php';
}
elseif ($_GET['videoChoice']=="5")
{
require 'videouploaddir.php';
}
$this->_types = $types;
$this->_lang = $lang;
$this->_upload_dir = $upload_dir;
$this->_maxsize = $maxsize;
$this->path = $PHP_SELF;
if (is_array($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
}
function allowTypes ()
{
$str = '';
if (count($this->_types) > 0) {
$str = 'Allowed types: (';
$str .= implode(', ', $this->_types);
$str .= ')';
}
return $str;
}
// private methods
function _doSafeUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if (exif_imagetype($this->_params['tmp_name']) && in_a rray(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -4);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this->_up load_dir.$this->new_name);
$this->imgurl =$this->new_name;
//$this->imgurl = .$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _doUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if(in_array(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -3);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this- >_upload_dir.$this->new_name);
$this->imgurl = ''.$this->new_name;
//$this->imgurl = ''.$this->_upload_dir.''.$this->new_name;
//$this->imgurl = ''.$this->new_name;
//$this->imgurl = $this->_upload_dir.'/'.$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _errorMsg()
{
$this->errorStr = implode('<br />', $this->_errors);
}
}
?>
You are getting that message because you are never checking if the user uploaded a file or not, you're just assuming they are. When the user does not upload a file then $_FILES will be an empty array.
That means that $this->_params['tmp_name'] won't exist. You need to check if a file was uploaded, not just assume one was.
Just simply check the size of $_FILES.
if(count($_FILES) === 0){
echo "no file uploaded";
}
Change your code to this one and then try
if (isset($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}