Submitting Image From Form Apparently Wrong Octet - php

A simple form with an image viewer below it in the same test.php script, the image gives errors in displaying. Disabling the headers and viewing the image data on the screen, it seems to have many of the little black ? diamonds all over it so probably somehow the wrong octet is being submitted. Where does the encoding get lost and how do I fix it?
To clarify, I am not trying to upload and save the file anywhere and I am not trying to insert it into a database. I simply want the data stream to directly display itself on the screen.
Also, the conditional around the PHP code is simply so that it does nothing until it receives a file. No validation needed as this is used only locally on my development system as a test tool.
test.php
<form method="POST" action="test.php" enctype="multipart/form-data">
<fieldset>
<legend>Image Functions Tester</legend>
<p><label for="image">Image</label>
<input type="file" name="fileToProcess" id="fileToProcess">
<p><input name="insert" type="submit" value="Upload">
</fieldset>
</form>
<?php
if (isset($_FILES['fileToProcess'])) :
$file = $_FILES['fileToProcess'];
$image = file_get_contents($file['tmp_name']);
// TEST ConvertImage() FUNCTON HERE
// Get the image mime type
$mimetype = Array("1" => "image/gif",
"2" => "image/jpeg",
"3" => "image/png",
"6" => "image/bmp");
// Add headers and output the image
Header("Pragma: no-cache");
Header('Content-type: ' . $mimetype[exif_imagetype($image)]);
echo $image;
endif;
?>

I guess you are trying to display uploaded image. in your code I see that you are trying to validate to ensure that user submit only images. In php they are just two best method to ensure that submitted files are not virus but image
1.) using Getimagesize Function
2.) Fileinfo method.
I have implemented the validation in your code to ensure workability.
First create a directory call uploads where files will be uploaded and run this your update code
<form method="POST" action="test.php" enctype="multipart/form-data">
<fieldset>
<legend>Image Functions Tester</legend>
<p><label for="image">Image</label>
<input type="file" name="fileToProcess" id="fileToProcess">
<p><div class="ButtonCenter">
<input name="insert" type="submit" value="Upload">
</div>
</fieldset>
</form>
test.php
<?php
if (isset($_FILES['fileToProcess'])) {
$uploadDir = "uploads/";
$filename= $_FILES['fileToProcess']['name'];
$file_types=array(
'image/gif',
'image/jpeg',
'image/png',
'image/jpg',
'image/GIF',
'image/JPEG',
'image/PNG',
'image/JPG'
);
// validate image using getimagesize function
$image_info =getimagesize($_FILES['fileToProcess']['tmp_name']);
//print_r($image_info);
$mime_image = $image_info['mime'];
// ensure the file is image via getimagesize function
if ( ! ( in_array($mime_image, $file_types) ) ) {
echo "you can only upload images";
exit();
}
//validate image using file info function
$f = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($f, $_FILES['fileToProcess']['tmp_name']);
if ( ! ( in_array($mime, $file_types) ) ) {
echo "You can only upload Images";
exit();
}
finfo_close($f);
if(move_uploaded_file($_FILES['fileToProcess']['tmp_name'],"$uploadDir/".$filename)) {
echo "File uploaded successfully";
echo "<img src='uploads/$filename' width='100px' height='100px'>";
}
}
?>

After fighting with this for two days, I just found the problem although I don't fully understand the reason it makes a difference. Apparently the form and the viewer cannot be on the same page so splitting them into two files works perfectly:
test.php
<?php
if (!isset($_FILES['fileToProcess'])) : ?>
<div class="PageCaption">Site Administration<hr></div>
<form method="POST" action="testviewer.php" enctype="multipart/form-data">
<fieldset>
<legend>Image Functions Tester</legend>
<p><label for="image">Image</label>
<input type="file" name="fileToProcess" id="fileToProcess">
<p><div class="ButtonCenter">
<input name="insert" type="submit" value="Upload">
</div>
</fieldset>
</form><?php
endif; ?>
testviewer.php
<?php
if (isset($_FILES['fileToProcess'])) :
$file = $_FILES['fileToProcess'];
$image = file_get_contents($file['tmp_name']);
// Get the image mime type
$mimetype = Array("1" => "image/gif",
"2" => "image/jpeg",
"3" => "image/png",
"6" => "image/bmp");
// Add headers and output the image
Header("Pragma: no-cache");
Header('Content-type: ' . $mimetype[exif_imagetype($image)]);
echo $image;
endif;?>

Related

php imagecreatefromjpeg not working

I am new to PHP, so this might be an easy one.
I just want to display an image once it is uploaded and sent to the script by POST. But I am not able to see the image.
Please find the code below:
Name of the php file is test.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_FILES['photo'])
&& is_uploaded_file($_FILES['photo']['tmp_name'])
&& $_FILES['photo']['error'] == UPLOAD_ERR_OK){
if ($_FILES['photo']['type']=='image/jpeg') {
$tmp_img = $_FILES['photo']['tmp_name'];
$image = imagecreatefromjpeg($tmp_img);
header('Content-Type: image/jpeg');
imagejpeg($image,'',90);
imagedestroy($image);
}else{
echo "Uploaded file was not JPEG","</br>";
}
}else{
echo "No file uploaded","</br>";
}
}else{
?>
<form action="test.php" method="post" enctype="multipart/form-data">
<label for="photo">Photo : </label>
<input type="file" name="photo"/>
<input type="submit" value="Upload a JPEG photo"/>
</form>
<?php } ?>
Do you get any errors?
Is GD installed? imagecreatefromjpeg is a GD method.
http://php.net/manual/en/image.installation.php
You need to pass NULL here:
imagejpeg($image,NULL,90);
From the documentation under Parameters:
filename
The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.
To skip this argument in order to provide the quality parameter, use NULL.

not worked upload video file via php

htm code :
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
Movie :<br />
<input name="fileField" type="file" size="30" /><br />
<input name="submit" type="submit" class="submit" value="Send" />
</form>
php code :
if ($_FILES['fileField']['tmp_name'] !=""){
$fileName = $_FILES["fileField"]["name"];
$fileType = $_FILES["fileField"]["type"];
$fileTmpLoc = $_FILES["fileField"]["tmp_name"];
$fileName = preg_replace('#[^a-z.0-9]#i', '', $fileName);
move_uploaded_file($fileTmpLoc, '../upload/video.flv');
}
this code not work for VIDEO file but work correct for other file ( jpeg , mp3 , png and ,,, )
Perhaps change your directory to
move_uploaded_file($fileTmpLoc, '../upload/ ');
this problem from php setting
php set to Max 2MB size for upload
You have absolutely no error handling on the code, meaning you have no way of telling when an upload failed. Add:
if ($_FILES['fileField']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error " . $_FILES['fileField']['error']);
}
as some bare-minimum error handling. The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php. Checking for the absence of a 'tmp_name' is NOT a proper check.

PHP-Jquery image upload not working

I'm trying to post form data through ajax
form1.php
I use request to get all URL parameter data
$_REQUEST["Ename"];
$_REQUEST["eImg"];
To upload the image,i use this code http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html
In the above link,you can see the source code,in the place of $_FILES['photoimg']['name'];,i use $_FILES['image']['name']; but it is not uploading the file and giving success message.
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
I removed script that is marked with **
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
**if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{**
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
if(strlen($name)) {
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats)) {
if($size<(1024*1024)) { // Image size max 1 Mb
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['image']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name)) {
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
} else {
echo "failed";
}
} else {
echo "Image file size max 1 MB";
}
} else {
echo "Invalid file format..";
}
} **else {
echo "Please select image..!";
exit();
}**
you simply can't upload files via $.ajax().
you'll have to use some trycky iframe-stuff or something like that to make this work. luckily, there are ready-to-go plugins for jquery to handle this for you (like $.ajaxForm() for example wich seems to be the one that's used in the tutorial you're reading).
EDIT:
the plugin also allows to add extra data thats not present in the form itself. to quote the documentation:
data
An object containing extra data that should be submitted along with the form.
data: { key1: 'value1', key2: 'value2' }
For upload image by ajax you should use an iframe and set its id to form target.
Please have a look at
http://www.coursesweb.net/ajax/upload-images
It is very simple code to upload image
That won't work!
Images are handled differently from the text data in Ajax so you would have to do more than just post it using the $.ajax({}) method.
You can however use the jquery.form.js plugin it works perfect http://jquery.malsup.com/form/#download there is a tutorial on how to use it
here
Any ways I have used it my self so let me elaborate for you.
The JavaScript code is here
$('.uploadForm').live('click', function(evt){
$('#feedback').html(' ');
$('#feedback').html('<img src="images/loader_image.gif" alt="Uploading...."/>');
$("#formID").ajaxForm({
target: '#feedback'
}).submit();
evt.preventDefault();
});
If your PHP code is fine this should work .....
Just post the rest of the form fields in the normal way way
This should work for you. If the PHP code is fine
For example if you had other form fields like firstname and lastname in form like this one
<div class="form">
<fieldset class="ui-corner-all">
<h3 class="ui-widget-header ui-corner-top" align="center">Client information</h3>
<form action="save_new_client.php" enctype="multipart/form-data" id="clientForm" method="POST">
<label>First Name</label>
<input name="firstname" type="text" id="firstname" class="required" minlength="3"/>
<label>Lastname</label>
<input name="date_added" type="text" id="date_added" class="dateEst" />
<label>Image</label>
<input name="photo" type="file" id="photo" />
<input type="submit" name="button" id="button" value="Save" class="uploadForm"/>
<input type="reset" name="reset" id="button" value="Cancel" /></td>
</form>
</fieldset>
<div id="feedback"></div>
</div>
Below it you'll just need to add a div or paragraph to hold your feedback message ....
then the rest will be just fine (like I said if your PHP code is okay)I have not looked through it alot

Uploading multiple images with one input field

i have created a photography website with an admin page that uploads photos to different categories in a mysql table. This much works, but i can only upload one file at a time and i'd like to be able to select multiple images.
Here's the form
<form action="index.php" enctype="multipart/form-data" name="myForm" id="myForm" method="post">
<select name="category" id="category">
<option value="Nature">Nature</option>
<option value="People">People</option>
<option value="Abstract">Abstract</option>
</select>
<input type="file" name="fileField" id="fileField" />
<input type="submit" name="submit" id="submit" value="Add Images" />
</form>
And here's the php for parsing the form
if (isset($_POST['submit'])) {
$category = mysql_real_escape_string($_POST['category']);
// Add this product into the database now
$sql = mysql_query("INSERT INTO images (category, date_added)
VALUES('$category',now())") or die (mysql_error());
$pid = mysql_insert_id();
// Place image in the folder
$newname = "$pid.jpg";
move_uploaded_file( $_FILES['fileField']['tmp_name'], "../photos/$newname");
header("location: thumbnail_generator.php");
exit();
}
I looked into the html5 file input method, and as far as i can tell, i can change the input as folllows:
<input type="file" name="fileField[]" id="fileField" multiple="multiple"/>
This allows me to select multiple files on the site, but i can't figure out how to implement this into my php. Any help would be much appreciated.
<form method="post" action="" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
Add Photos <input multiple="true" onchange="this.form.submit()" type="file" name="photos[]"/>
<input type="hidden" name="sendfiles" value="Send Files" />
</form>
<?php
define ("MAX_SIZE","5000");
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$errors=0;
if(isset($_POST['sendfiles']))
{
$uploaddir = "files/"; //a directory inside
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
echo "\n This is the extension: ",$extension;
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
//print error message
?>
<h4>Unknown extension!</h4>
<?php
$errors=1;
}
else
{
$size=filesize($_FILES['photos']['tmp_name'][$name]);
if ($size > MAX_SIZE*1024)
{
?>
<h4>You have exceeded the size limit!</h4>
<?php
$errors=1;
}
$image_name=$filename.'.'.$extension;
$newname="files/".$image_name;
$copied = copy($_FILES['photos']['tmp_name'][$name], $newname);
if (!$copied)
{
?>
<h4>Copy unsuccessfull!</h4>
<?php
$errors=1;
}
}
}
//echo "Images uploaded successfully";
}
//mysql_close($dbhandle);
?>
You are probably looking for something like uploadify or swfupload or plupload.
It works as-if there were multiple file fieldsĀ­Docs, it's transparent to PHP. Here is some simple example code:
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileField[]" id="fileField" multiple="multiple">
<input type="text" name="test" value="test">
<input type="submit" name="submit">
</form>
</body>
</html>
<?php
var_dump($_FILES, $_POST);
Store it on your host and request it. You can then play around with it, it will show you the structure of the $_FILES and $_POST array.
Example output:
array
'fileField' =>
array
'name' =>
array
0 => string 'hakre-iterator-fun-cut-top.png' (length=30)
1 => string 'hakre-iterator-fun-cut-middle.png' (length=33)
'type' =>
array
0 => string 'image/png' (length=9)
1 => string 'image/png' (length=9)
'tmp_name' =>
array
0 => string '/tmp/php1A2.tmp' (length=15)
1 => string '/tmp/php1A3.tmp' (length=15)
'error' =>
array
0 => int 0
1 => int 0
'size' =>
array
0 => int 234001
1 => int 213058
array
'test' => string 'test' (length=4)
'submit' => string 'Submit' (length=6)
See Uploading multiple filesĀ­Docs.
Simple! Just Add multiple="true" to your input tag.
<input name "example" type="file" multiple="true"/>
Try out this.
http://www.uploadify.com/demos/
Uploadify is a powerful and highly-customizable file upload script. Uploadify is easy to get up and running with
minimal effort and little coding knowledge.
you will receive an array of images -> fileField[]. Just iterate through this array and add the images the same way you were adding them before. Also, I'd suggest using this, very nice script - http://valums.com/ajax-upload/
EDIT: Just don't forget to implement at least some security checks, like min and max upload size, file extensions and mime-type checking! Even if it's for the back-end, this could still lead to unpleasant events.
Wouldn't something like creating an array work too? So what he could do is
$images = array();
Then in his form just add a add to image list button? From there he just keep adding as many images as he wants and then just iterate over the array and add to the database?

Uploading a .jar with php problem

I am building a php application.
I can easily upload an image or any other type of data, but not a .jar. Below my code:
Upload.php
<form action="getfile.php" method="post" name="uploadForm" id="uploadForm" enctype="multipart/form-data" ><br>
<?php echo gettext("Image "); ?>
<input name="imagen" value="" type="file" id="imagen" />
<?php echo gettext("Jar "); ?>
<input name="jarFile" value="" type="file" id="jarFile" />
</form>
getfile.php
$fileName = $_FILES['jar']['name'];
$fileType = $_FILES['jar']['type'];
//Check the extension
if (!strpos($fileType, "jar") ) {
echo gettext("The simulation must be jar extension. Try again.");
}else{
if (move_uploaded_file($_FILES['jar']['tmp_name'], $path)){
echo gettext("Simulation stored succesfully.");
}else{
echo gettext("Something happened. Try again. ");
}
}
For images I am following the same aproach, but when I try to upload a jar file, I am always getting the error
The simulation must be jar extension. Try again
and $fileType is empty. Is there some restriction at this point? Am I missing something??
Thanks in advance
The type property is unreliable (and populated by the browser). Your best bet is to retrieve the MIME file type:
$fhandle = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($fhandle, $_FILES['jar']['tmp_name']);
The $mime_type should be application/java-archive.
PHP >= 5.3.0

Categories