the following piece of code recognizes the image through getimagesize() but then when i try to move the file to an uploaded folder it moves the file there but says it's an array? im confused because im not setting any variables as an array?
<?php
//simple image check using getimagesize() instead of extensions
if($_FILES){
$empty_check = getimagesize($_FILES['file']['tmp_name']);
if(empty($empty_check)){
echo 'this is not an image';
}
else{
echo 'you have uploaded ' . explode('.',$_FILES['file']['name'])[0].'
and it is a ' . explode('.',$_FILES['file']['name'])[1].'.';
//an example of how i would extract the extension
$target = "C:\\xampp\\htdocs";
move_uploaded_file($_FILES['file']['tmp_name'], $target.'\\'.$_FILES['file']);
}
}
?>
$_FILES['file']
is an array, you're trying to use it as the target filename;
comment of deceze.
Echo the file you want to move/save, then you should see what he mentioned..
When using move_uploaded_file you get to pick the filename, so you can pick anything you want.
When you upload the file, its put into a temporary directory with a temporary name, move_uploaded_file() allows you to move that file and in that you need to set the name of the file as well.
Use this coding for multiple file uploading....
//For Multiple file uploading
if (isset($_FILES['photo']) != "") {
$errors = array();
foreach($_FILES['photo']['tmp_name'] as $key = > $tmp_name) {
$file_name = $_FILES['photo']['name'][$key];
$file_size = $_FILES['photo']['size'][$key];
$file_tmp = $_FILES['photo']['tmp_name'][$key];
$file_type = $_FILES['photo']['type'][$key];
//change the image extension as png
$fileExt = "png";
$photorename[$key] = strtolower($property_code.
'_'.$key.
'.'.$fileExt);
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
//Path of Uploading file
$target = "images_property";
if (empty($errors) == true) {
if (is_dir($target) == false) {
mkdir("$target", 0700); // Create directory if it does not exist
}
if (file_exists("$target/".$photorename[$key])) {
unlink("$target/".$photorename[$key]);
}
move_uploaded_file($file_tmp, "$target/".$photorename[$key]);
} else {
print_r($errors);
}
}
if (empty($errors)) {
echo "Success";
}
}
Related
Code
if(is_array($_FILES) && isset($_FILES['photography_attachment'])) {
if(is_uploaded_file($_FILES['photography_attachment']['tmp_name'])) {
$fileName = $_FILES["photography_attachment"]["name"]; // The file name
$fileTmpLoc = $_FILES["photography_attachment"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["photography_attachment"]["type"]; // The type of file it is
$fileSize = $_FILES["photography_attachment"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["photography_attachment"]["error"]; // 0 = false | 1 = true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!$fileTmpLoc) { // if file not chosen
$error = $error."<p>Please browse for a file before clicking the upload button.</p>";
} else if($fileSize > 10485760) { // if file size is larger than 2 Megabytes
$error = $error."<p><span>Your file was larger than</span> 10 <span>Megabytes in size</span>.</p>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if (!preg_match("/.(gif|jpg|png|jpeg)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
$error = $error."<p>Your file was not .gif, .jpg, .png</p>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
$error = $error."<p>An error occured while processing the file. Try again.</p>";
}
}else{ $error = "Please try again !!!"; }
}else{ $error = "Attachment field cannot be blank!"; }
Always goto "Please try again !!!" else while uploading image in windows, but it worked well in linux system.
Can you please any one help me for this issue?
On windows platforms you musst replace inside the file path the "\" with an "/"
Like this:
$file = str_replace ("\\", "/", $_FILES['photography_attachment']['tmp_name']);
if(is_uploaded_file($file)) {
[...]
}
Or use the php build in method, for all systems:
$file = realpath($_FILES['photography_attachment']['tmp_name']);
if(is_uploaded_file($file)) {
[...]
}
I am uploading file into folder using PHP but my issue is its at a time writing file into 2 different path. My code is below.
if(array_key_exists('pimage',$_FILES)){
$tempFile = $_FILES['pimage']['tmp_name'];
$fileName = $_FILES['pimage']['name'];
$fileName = str_replace(" ", "-", $_FILES['pimage']['name']);
$fig = rand(1, 999999);
$saveFile = $fig . '_' . $fileName;
$uploadOk = 1;
if (exif_imagetype($_FILES['pimage']['tmp_name']) == IMAGETYPE_GIF) {
$ext=pathinfo($saveFile, PATHINFO_FILENAME);
$saveFile=$ext.'.png';
$png = imagepng(imagecreatefromgif($_FILES['pimage']['tmp_name']), $saveFile);
}
if (exif_imagetype($_FILES['pimage']['tmp_name']) == IMAGETYPE_JPEG) {
$ext=pathinfo($saveFile, PATHINFO_FILENAME);
$saveFile=$ext.'.png';
$png = imagepng(imagecreatefromjpeg($_FILES['pimage']['tmp_name']), $saveFile);
}
if (strpos($fileName,'php') !== false) {
# code...
}else{
$targetPath = PT_USERS_IMAGES_UPLOAD;
$targetFile = $targetPath . $saveFile;
if (file_exists($targetFile)) {
$data=array("msg"=>'profile image already exists');
$uploadOk = 0;
}
if ($_FILES["pimage"]["size"] > 2000000 || $_FILES["pimage"]["size"] == 0) {
$uploadOk = 0;
$data=array("msg" => "profile image should not greater than 2 MB.");
}
//echo $uploadOk;exit;
if ($uploadOk==0) {
$flag=0;
$data[]=array("msg" => $data['msg']);
}else{
$moved =move_uploaded_file($tempFile, $targetFile);
if ($moved) {
$filename = $saveFile;
$data = array('ai_image' => $filename);
$this->db->where('accounts_id', $dataArr['user_id']);
$this->db->update('pt_operator_accounts', $data);
}else{
$flag=0;
$data[]=array("msg" => "Not uploaded because of error #".$_FILES["pimage"]["error"]);
}
// print_r($data);exit;
}
}
}
Here I need to write file into PT_USERS_IMAGES_UPLOAD path but before uploading into this path also the file is uploading into project's root path. Here I need to upload only in PT_USERS_IMAGES_UPLOAD path not in project's root path.
It is likely because of these lines:
imagepng(imagecreatefromgif($_FILES['pimage']['tmp_name']), $saveFile);
If you look at the documentation regarding this imagepng(), it will either output an image to the browser (with a proper header) or save the file to disk when you fill out the second parameter, in your case you have used the to parameter ($saveFile). So, once you save it there, you then save it again using the move_uploaded_file($tempFile, $targetFile); which is the one saving it to the proper location.
If you are trying to convert something to PNG, then just do the imagepng() line and remove the move_uploaded_file() line. Change $saveFile to T_USERS_IMAGES_UPLOAD and then you should only get one saved file. Either way, remove one of those methods for saving the file to disk.
I try using function to upload different kind of file by giving it variables. As shown below:
<?
function fn_fileUpload($data,$dir,$uid){
include_once($_SERVER['DOCUMENT_ROOT']."/cgi-bin/connect.php");
if(isset($data) && $data['error'] === UPLOAD_ERR_OK){
$fileTmpPath = $data['tmp_name'];
$fileName = $data['name'];
$fileSize = $data['size'];
$fileType = $data['type'];
$fileNameCmps = explode(".", $fileName);
$fileExt = strtolower(end($fileNameCmps));
$newFileName = $uid . '.' . $fileExt;
//check file ext
$okEXT = array('jpg', 'jpeg', 'png','doc','docx','pdf');
if (in_array($fileExt, $okEXT)) {
$fileDir = '/'.$dir.'/';
$dest_path = $fileDir.$newFileName;
if(move_uploaded_file($fileTmpPath, $dest_path)){
try{
$stmt2=$mysqli->prepare("insert into job_file (jfile_id, job_id, jfile_name, jfile_size, jfile_type, jfile_ext) valies(?,?,?,?,?,?)");
$stmt2->bind_param('iisiss',$zero,$uid,$newFileName,$fileSize,$fileType,$fileExt);
$stmt2->execute();
$result = 'ok';
}catch(mysqli_sql_exception $err){
$result=$err;
}
}else{
$result = 'Cannot upload file!';
}
}//in_array
}//if(isset
return $result;
}
?>
And this is how to use:
//upload file
$job_file=fn_fileUpload($_FILES['job_file'],'uploads',$_POST['passport_id']);
//upload photo
$job_img=fn_fileUpload($_FILES['job_img'],'photos',$_POST['passport_id']);
From here, the function always return : Cannot upload file!. At first I think. It might have something to do with move_uploaded_file but the file was there in /uploads directory but not with /photos. Both directories CHMOD 755 (tried 777 but no luck).
The db went through correctly. Is there any idea how to fix this?
You can only use move_uploaded_file() ONCE on a temporary file that has been uploaded through a form. This function destroys the temporary file after it has been moved, so the for the first upload in the uploads directory you can do it well but in for the second one no.
Please could someone show me where i need to change the code so that the image uploaded is renamed to "freddy" for e.g.
But still carries the correct existing extension i.e jpg, png, gif.
Thanks In Advance
<?php
// define a constant for the maximum upload size
define ('MAX_FILE_SIZE', 1024 * 50);
if (array_key_exists('upload', $_POST)) {
// define constant for upload folder
define('UPLOAD_DIR', '/home/richard/public_html/testing/editable-images/');
// replace any spaces in original filename with underscores
$file = str_replace(' ', '_', $_FILES['image']['name']);
// create an array of permitted MIME types
$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg',
'image/png');
// upload if file is OK
if (in_array($_FILES['image']['type'], $permitted)
&& $_FILES['image']['size'] > 0
&& $_FILES['image']['size'] <= MAX_FILE_SIZE) {
switch($_FILES['image']['error']) {
case 0:
// check if a file of the same name has been uploaded
// Uncomment to stop overwritten files >>>> if (!file_exists(UPLOAD_DIR . $file)) {
// move the file to the upload folder and rename it
$success =
move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR .
$file);
// Uncomment to stop overwritten files >>>> } else {
// Uncomment to stop overwritten files >>>> $result = 'A file of the same name already exists.';
// Uncomment to stop overwritten files >>>>> }
if ($success) {
$result = "$file uploaded successfully.";
} else {
$result = "Error uploading $file. Please try again.";
}
break;
case 3:
case 6:
case 7:
case 8:
$result = "Error uploading $file. Please try again.";
break;
case 4:
$result = "You didn't select a file to be uploaded.";
}
} else {
$result = "$file is either too big or not an image.";
}
}
?>
// get file extension
$ext = end(explode($_FILES['image']['name']));
// name your file and preserve file extension
$file = "freddy.".$ext;
// create an array of permitted MIME types
....
Check description of method move_uploaded_file here
I have a simple PHP upload script I have started. I am not the best to PHP. Just looking for some suggestions.
I want to limit my script to only .JPG, .JPEG, .GIF and .PNG
Is this possible?
<?php
/*
Temp Uploader
*/
# vars
$mx=rand();
$advid=$_REQUEST["advid"];
$hash=md5(rand);
# create our temp dir
mkdir("./uploads/tempads/".$advid."/".$mx."/".$hash."/", 0777, true);
# upload dir
$uploaddir = './uploads/tempads/'.$advid.'/'.$mx.'/'.$hash.'/';
$file = $uploaddir . basename($_FILES['file']['name']);
// I was thinking of a large IF STATEMENT HERE ..
# upload the file
if (move_uploaded_file($_FILES['file']['tmp_name'], $file)) {
$result = 1;
} else {
$result = 0;
}
sleep(10);
echo $result;
?>
Yes, quite easily. But first off, you need some extra bits:
// never assume the upload succeeded
if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES['file']['error']);
}
$info = getimagesize($_FILES['file']['tmp_name']);
if ($info === FALSE) {
die("Unable to determine image type of uploaded file");
}
if (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
die("Not a gif/jpeg/png");
}
Relevant docs: file upload errors, getimagesize and image constants.
File path isn't necessarily the best way to check if an image really is an image. I could take a malicious javascript file, rename it to have the .jpg extension, and upload it. Now when you try to display it in your website, I may have just compromised your site.
Here is a function to validate it really is an image:
<?php
function isImage($img){
return (bool)getimagesize($img);
}
?>
try this:
<?php
function isimage(){
$type=$_FILES['my-image']['type'];
$extensions=array('image/jpg','image/jpe','image/jpeg','image/jfif','image/png','image/bmp','image/dib','image/gif');
if(in_array($type, $extensions)){
return true;
}
else
{
return false;
}
}
if(isimage()){
//do codes..
}
?>
Or take a look at: http://php.net/manual/en/function.pathinfo.php
if (substr($_FILES["fieldName"]["name"], strlen($_FILES["fieldName"]["name"])-4) == ".jpg")
{
if(move_uploaded_file($_FILES["fieldName"]["tmp_name"],$path."/".$_FILES['fieldName']['name']))
{
echo "image sucessfully uploaded!";
}
}
similarly you can check for other image formats too.