php html file upload form validation error - php

Im having problems with form validation. When I dont select a file for upload I still get an error that promts only png images valid. I thought that if no file was selected the $_FILES array would be empty.
What am I doing wrong?
my html form excerpt for file upload looks like this:
<label for="file">Filename
<span class="small">Upload image</span>
</label>
<input type="file" name="file" id="file">
my php processing looks like this:
$submitted_file = $_FILES['file'];
if(isset($submitted_file)) {
// verify the file PNG only
$fileType = exif_imagetype($submitted_file["tmp_name"]);
$allowed = array(IMAGETYPE_PNG);
$max_filesize = 512000;
if (!in_array($fileType, $allowed)) {
$proceed = false;
$arrErrors['submitted_file_ext'] = 'Please upload .png images only.';
}
}

The array that you are checking should have the field ["tmp_name"] as null if it is blank. Try this code instead:
if(!empty($submitted_file["tmp_name"])) {

The right way is to check $_FILES['error']
if ($_FILES['name']['error'] === UPLOAD_ERR_OK) {
// file successfully uploaded
}
More info here http://ru2.php.net/manual/en/features.file-upload.php

Related

why do i have a corrupted image file after using move_uploaded_file function

I have a form:
<form action='' enctype="multipart/form-data" method="post">
<input type="file" name="image">
<input type="submit" value="send">
</form>
I have php code:
$file = $_FILES['image']
$ext = explode(",", $file['type'])[0];
$location = "../image/movedimage.$ext";
if(move_uploaded_file($file['tmp_name'], $location)) echo 'moved';
else echo 'internal error';
This echos "moved" but the problem is that when I check the path to which the file was moved, the image file in there is corrupted.
I had to change the system of uploading the image by doing this:
$file_content = file_get_contents($file['tmp_name']);
$file_dump = file_put_contents($location, $file_content);
This attempt of placing the file directly using the file_put_contents works fine and the image file is perfect just as uploaded but using the move_uploaded_file leaves a corrupted file in the destination folder. I would like to understand why this is happening as the $file['error'] returns a value 0 and the move_uploaded_file function does not return false.
In your code by using
$ext = explode(",", $file['type'])[0];
you get the extension as image/your_image_type.
Then you are appending that with the file name, which will create an invalid image.
To get the extension, you can do as follows
$ext= explode("/", $file['type'])[1];
or
$ext = strtolower(end(explode('.',$_FILES['image']['name'])));

PHP Upload image then show

I'm trying to figure out how to allow image upload with the image showing up after it is uploaded. I have found this tutorial on uploading images but I'm not sure how to display them afterwards. Would I have to save it in the database then pull it up afterwards somehow?
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
I think you would benefit from an uploading class or function that returns information for your uploaded image. This will help you store the results or display as you are looking to do. Here is one loosely based on what you provided with notation:
Form:
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
Script:
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'];
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
To use:
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
RAW Feedback:
// This is what the array would look like on return of successful upload:
Array
(
[filename] => animal.png
[fullpath] => /data/19/2/133/150/2948313/user/2524254/htdocs/mydomain/uploads/animal.png
[localpath] => /uploads/animal.png
[filesize] => 35702
)
yes,you would have to save the path to the file in the database and fetch it but for your use case,you can save the path to a $_SESSION variable and then echo the path immediately the script is done.
But you first have to complete the file transfer with the move_uploaded_file function as without that,you would not be able to retrieve the file path as they are stored as temporary files and deleted once the script is interpreted
http://php.net/manual/en/function.move-uploaded-file.php
After this is done,you are to get the path to the file and use the normal img HTML tag
create <img src="" widht="" height="" /> forever u must move the image to directory path and now i get the image name from table after submit the form.. and given the url to img..example.. ur directory name uploads/img . now your file name save in database table as image01.jpg . sample
$img= 'select imagename from table name ';
if(count($img))
{
<img src="<?php echo 'uploads/img/'.$img" widht="10px" height="20px" /></div>
}
if you upload image on data base , data loading will be slow because image siz too large. better method is upload image in folder & save image file path in data base .when you retrieve image call image web root on image tag
example
Saving Filepath Of Uploaded Image To MySQL Database
GET image path
name refers to the filename on the client-side. To get the filename (including the full path) on the server-side, you need to use tmp_name:
$check = fopen($_FILES["UploadFileName"]["tmp_name"], 'r');

HTML form file not uploading

I have an HTML form as the following:
<form id="addTrack" action="/worship/script/upload.php" method="post" enctype="multipart/form-data">
<label>File:</label>
<input type="file" name="uploaded" id="addTrackFile"/>
<label>Key Title: </label>
<input type="text" name="title" id="addTrackTitle"/>
<input type="hidden" name="id" id="addTrackId"/><br>
</form>
<button onclick="uploadAddTrack()">Upload</button>
<button onclick="closeAddTrack()">Close</button>
When I submit the form the file uploads to the server properly, but when it gets redirected to the PHP action script, it gets stopped at the first error catch. The script then dumps the $_FILES variable which it returns as an empty array. As you can see in the code below, I also have it echo the error, but it also echoes an empty string.
Why am I not getting a file in the $_FILES array?
My PHP Code:
$id=$_POST["id"];
$name=$_POST["title"];
$name = str_replace(" ","",$name);
$allowed_filetypes = array('.mp3','.m4a','.wav','.wma');
$filename = $_FILES['uploaded']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
$target = "../audio/";
$target = $target . $id. "_".$name.$ext;
$ok=1;
if ($_FILES['uploaded']['error'] !== UPLOAD_ERR_OK) {
//------------This is where it gets stopped-----------------//
var_dump($_FILES);
echo $_FILES["uploaded"]["error"];
return;
}
if(!in_array($ext,$allowed_filetypes))
die("This file type is not allowed");
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
include("updateDB.php");
header("Location:/worship/cpanel/?autoload=$id");
}
The size of the file I am uploading is 9mb.
My php.ini relevant info
file_uploads: On
upload_max_filesize: 25M
upload_tmp_dir: no value
max_post_size: 8M
check you PHP.ini file. make sure the POST size is larger the 8M. because that is the default and you're sending info that is 9MB.
`; Maximum size of POST data that PHP will accept.
post_max_size = 8M`

Resize and rename PNG, JPG or GIF file with PHP

is there any way, using PHP, that you can resize an image sent from a HTML form's WIDTH (Only PNG, JPG and GIF) to a max value of let's say 500px (so if the file is 350px wide there isn't any stretching), and rename it to a random 15 character name (e.g. "e19gy675jo5el7g.png") and save it to the image/ directory?
I have some code already but it doesn't resize the file and allows all file types to be uploaded (it only renames the file to a random name). I don't want to use the accept="image/*" HTML code in the form so if you could help me find a PHP solution that would be great.
Here's my PHP code...
<?php
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['uploaded']['name']) ;
$ran = rand () ;
$ran2 = $ran.".";
$target = "image/";
$target = $target . $ran2.$ext;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file has been uploaded as ".$ran2.$ext;
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
?>
And here's my HTML
<html>
<body>
<form enctype="multipart/form-data" action="upload.php" method="post">
<div>
<input name="uploaded" type="file" />
</div>
<br>
<button type="submit">Upload</button>
</form>
</body>
</html>
Sorry for the complicated question, I'm just quite new with PHP :-)
Thanks in advance :-)
I don't know the whole code but you can do it by GD library of PHP.Use
getimagesize($filename)
TO get the image details and check the width using it.If width is less than 500 then do not resize.
Link that may help you: http://forums.phpfreaks.com/topic/210603-uploaded-image-change-width-and-height/

PHP upload image

Alright I have way to much time invested in this. I am new to PHP programming and trying to grasp the basics, but I am a little lost as of last night I was able to get a PHP form to upload basic data like a name address and stuff to my (MySQL) server.
But today I said let's do the next step which would be an image to the server.
I have watched 3 videos on YouTube probably a 100 times just recoping code and trying it in so many different ways.
http://www.youtube.com/watch?v=CxY3FR9doHI
http://www.youtube.com/watch?v=vFZfJZ_WNC4&feature=relmfu
and still haven't been able to get it.
But long story short: I have a config.php file that connects to the server and here is the the code I'm running on the upload form page:
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<form action="UploadContent.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="Upload">
</form>
<?php
// connect to database
include"config.php";
// file properties
$file = $_FILES['image']['tmp_name'];
if (!isset($file))
echo "Please select a profile pic";
else
{
$image = addslashes(file_get_content($_FILES['image']['tmp_name']));
$image_name = addslashes($FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if ($image_size==FALSE)
echo "That isn't a image.";
else
{
$insert = mysql_query("INSERT INTO content VALUES ('','','','','','','','','','$image_name','$image',)");
}
}
?>
</body>
</html>
The reason for all the '', '', '', '' on the insert line is because I have the name in the 10th field and the image blob in the 11th and all the ones leading up to that are first name, last name and random stuff like that. How can I fix this? It is returning the error:
Fatal error: Call to undefined function file_get_content() in /home/content/34/9587634/html/WEBPAGE/UploadContent.php on line 22
I don't know what to do.
The code overlooks calling the function move_uploaded_file() which would check whether the indicated file is valid for uploading.
You may wish to review a simple example at:
http://www.w3schools.com/php/php_file_upload.asp
You need to add two new file one is index.html, copy and paste the below code and other is imageup.php which will upload your image
<form action="imageup.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner" >
<input type="submit" value="submit">
</form>
imageup.php
<?php
$banner=$_FILES['banner']['name'];
$expbanner=explode('.',$banner);
$bannerexptype=$expbanner[1];
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Yh:i:sa', time());
$rand=rand(10000,99999);
$encname=$date.$rand;
$bannername=md5($encname).'.'.$bannerexptype;
$bannerpath="uploads/banners/".$bannername;
move_uploaded_file($_FILES["banner"]["tmp_name"],$bannerpath);
?>
The above code will upload your image with encrypted name
Change function file_get_content() in your code to file_get_contents() . You are missing 's' at the end of function name. That is why it is giving undefined function error.
file_get_contents()
Remove last unnecessary comma after $image filed in line
"INSERT INTO content VALUES ('','','','','','','','','','$image_name','$image',)
I would recommend you to save the image in the server, and then save the URL in MYSQL database.
First of all, you should do more validation on your image, before non-validated files can lead to huge security risks.
Check the image
if (empty($_FILES['image']))
throw new Exception('Image file is missing');
Save the image in a variable
$image = $_FILES['image'];
Check the upload time errors
if ($image['error'] !== 0) {
if ($image['error'] === 1)
throw new Exception('Max upload size exceeded');
throw new Exception('Image uploading error: INI Error');
}
Check whether the uploaded file exists in the server
if (!file_exists($image['tmp_name']))
throw new Exception('Image file is missing in the server');
Validate the file size (Change it according to your needs)
$maxFileSize = 2 * 10e6; // = 2 000 000 bytes = 2MB
if ($image['size'] > $maxFileSize)
throw new Exception('Max size limit exceeded');
Validate the image (Check whether the file is an image)
$imageData = getimagesize($image['tmp_name']);
if (!$imageData)
throw new Exception('Invalid image');
Validate the image mime type (Do this according to your needs)
$mimeType = $imageData['mime'];
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($mimeType, $allowedMimeTypes))
throw new Exception('Only JPEG, PNG and GIFs are allowed');
This might help you to create a secure image uploading script with PHP.
Code source: https://developer.hyvor.com/php/image-upload-ajax-php-mysql
Additionally, I suggest you use MYSQLI prepared statements for queries to improve security.
Thank you.
Simple PHP file/image upload code on same page.
<form action="" method="post" enctype="multipart/form-data">
<table border="1px">
<tr><td><input type="file" name="image" ></td></tr>
<tr><td> <input type="submit" value="upload" name="btn"></td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$image=$_FILES['image']['name'];
$imageArr=explode('.',$image); //first index is file name and second index file type
$rand=rand(10000,99999);
$newImageName=$imageArr[0].$rand.'.'.$imageArr[1];
$uploadPath="uploads/".$newImageName;
$isUploaded=move_uploaded_file($_FILES["image"]["tmp_name"],$uploadPath);
if($isUploaded)
echo 'successfully file uploaded';
else
echo 'something went wrong';
}
?>
Here is a basic example of how an image file with certain restrictions (listed below) can be uploaded to the server.
Existence of the image.
Image extension validation
Checks for image size.
<?php
$newfilename = "newfilename";
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$expensions= array("jpeg","jpg","png");
if(file_exists($file_name)) {
echo "Sorry, file already exists.";
}
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$newfilename.".".$file_ext);
echo "Success";
echo "<script>window.close();</script>";
}
else{
print_r($errors);
}
}
?>
<html>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<input type="submit"/>
</form>
</body>
</html>
Credit to this page.
<?php
$filename=$_FILES['file']['name'];
$filetype=$_FILES['file']['type'];
if($filetype=='image/jpeg' or $filetype=='image/png' or $filetype=='image/gif')
{
move_uploaded_file($_FILES['file']['tmp_name'],'dir_name/'.$filename);
$filepath="dir_name`enter code here`/".$filename;
}
?>
<?php
$target_dir = "images/";
echo $target_file = $target_dir . basename($_FILES["image"]["name"]);
$post_tmp_img = $_FILES["image"]["tmp_name"];
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$post_imag = $_FILES["image"]["name"];
move_uploaded_file($post_tmp_img,"../images/$post_imag");
?>
This code is very easy to upload file by php. In this code I am performing uploading task in same page that mean our html and php both code resides in the same file. This code generates new name of image name.
first of all see the html code
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="banner_image" >
<input type="submit" value="submit">
</form>
now see the php code
<?php
$image_name=$_FILES['banner_image']['name'];
$temp = explode(".", $image_name);
$newfilename = round(microtime(true)) . '.' . end($temp);
$imagepath="uploads/".$newfilename;
move_uploaded_file($_FILES["banner_image"]["tmp_name"],$imagepath);
?>

Categories