PHP Fatal error with uploading file from iphone - php

I am trying to create a webpage to upload an image from iPhone's photo library or take an image using iPhone's camera.
This is the error message on my iphone
This is the html code to upload the image
<html>
<form action="test_upload_image_results.php" method="post" enctype="multipart/form-data">
Select image to upload:
<br><input type="file" name="imageUpload" id="imageUpload">
<br><br><input type="submit" value="Upload Image" name="submit">
</form>
</html>
This is the php code (test_upload_image_results.php) used to upload the image
<html>
<body>
<?php
print_r($_FILES);
$tmpName = $_FILES["imageUpload"]["tmp_name"];
$destDir = "uploads/";
if (!is_dir($destDir))
{
throw new Exception('Destination is not a directory.');
}
if (!is_writable($destDir))
{
throw new Exception('Destination directory is not writable.');
}
$destination = $destDir.basename($_FILES["imageUpload"]["name"]);
if (is_file($destination))
{
throw new Exception('Destination filename already exists.');
}
if (move_uploaded_file($tmpName, $destination))
{
echo "done";
}
else
{
throw new Exception('Unable to move file.');
}
?>
</body>
</html>
Sorry if this is a very elementary question.

Because your php ini config upload_max_filesize is lower than size of uploading image.
Try to change upload_max_filesize to bigger one in php.ini
For more, see file eupload error codes at php.net doc http://php.net/manual/en/features.file-upload.errors.php

Looking at the error, there is no value set for $imageUpload['tmp_name'] and size is 0 - the image has not been uploaded
The error 1 indicates
"The uploaded file exceeds the upload_max_filesize directive in php.ini"
See http://php.net/manual/en/features.file-upload.errors.php

Related

I wanna read data from txt file but file_get_contents refuses to read uaing Array so how can i read it my code is here

I am using an HTML form to upload files. Then I use files array to convert them to variable then I am trying to read this variable.
My code is here :
if(isset($_POST['upload'])) {
$image = $_FILES['sfile'];
$contents = file_get_contents($image);
$links = explode(',',$contents);
echo $links[0];
}
Its called from the following form
<html>
<head>
<title> Trial </title>
</head>
<body>
<form align="center" method="post" action="example.php" enctype="multipart/form-data">
Upload File Here : <input type="file" name="sfile"><br>
<input type="submit" name ="upload" value="Upload">
</form>
</body>
</html>
You should read it from tmp_name, see the code below:
if (!empty($_FILES['sfile'])) {
$sfile = $_FILES['sfile'];
if ($sfile['error'] != UPLOAD_ERR_OK) {
// output error here
} else {
$contents = file_get_contents($sfile['tmp_name']);
$links = explode(',', $contents);
echo $links[0];
}
}
The $_FILES has this array format:
$_FILES['myfile']['name'] - the original file name
$_FILES['myfile']['type'] - the mime type
$_FILES['myfile']['size'] - the file size
$_FILES['myfile']['tmp_name'] - temporary filename
$_FILES['myfile']['error'] - error code
Error codes, from http://php.net/manual/en/features.file-upload.errors.php:
UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the
upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the
MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially
uploaded.
UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR Value: 6; Missing a temporary folder. Introduced
in PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE Value: 7; Failed to write file to disk.
Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION Value: 8; A PHP extension stopped the file
upload. PHP does not provide a way to ascertain which extension caused
the file upload to stop; examining the list of loaded extensions with
phpinfo() may help. Introduced in PHP 5.2.0.
Looking at http://php.net/manual/en/features.file-upload.post-method.php
Where you declare $image, it should be $_FILES['sfile']['tmp_name'];
The temporary filename of the file in which the uploaded file was stored on the server.

PHP uploading 0 bytes image

When I upload an imagen with PHP, I get no errors and the image is 0 bytes on server.
Things considered:
File_uploads is On in phpinfo()
Upload_max_filesize is 8M in phpinfo()
Upload_tmp_dir is set and has 777 permisions
If I run file_exists($_FILES['userfile']['tmp_name']), it returns
true
If i run getimagesize($_FILES['userfile']['tmp_name']), I get an Read
Error notice. The image is valid and can be opened with system image
viewer
I am using a very simple upload script for testing:
HTML:
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
PHP:
<?php
//$uploaddir = '/var/www/html/upload';
$uploaddir = '';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
When I submit the file, I get no errors and the image is created in the destination folder, with the correct name and extension, but as the title says, it is 0 bytes (of course, it can't be oppened).
Thanks for your time.
EDIT
Sajad Karuthedath just made me see that $_FILE['file']['size'] value is 0 !! What can be the problem causing files are not being uploaded correctly?
EDIT 2
Uploading txt, pdf, tar files is working properly.. The problem is only with image type files!
try this simple upload script ,
you should check for errors before saving to server
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$_FILES['file']['name']);
}
Note: don't forget to restart your server or xampp after changing phpinfo()
Note: also change post_max_size = 25M in php
In order to track the issue just add an "exit;" straight after the "move_uploaded_file..." command and if the file is properly uploaded it's the code after the "move_upload" which is wrong.
In my case I was opening the uploaded file after upload with an overwrite (w+) option in order to check the lock state of the file. which was making a empty file.

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);
?>

Possible Reasons Why a PHP File Upload Wouldn't Work

Here is the HTML:
<h1>Upload Custom Logo</h1>
<form action="settings.php" enctype="multipart/form-data" method="post">
<input type="file" name="Logo" />
<input type="submit" value="Upload" name="logoUpload" />
</form>
Here is the PHP:
<?php /* Handle Logo Upload */
if($_POST['logoUpload']) {
$target_path = "uploads/";
$Logo = $_FILES['Logo']['name'];
$target_path = $target_path . basename( $_FILES['Logo']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo '<div class="statusUpdate">The file '. basename( $_FILES['Logo']['name']).
' has been uploaded</div>';
}
} else{
echo '<div class="statusUpdate">There was an error uploading the file to: '.$target_path.', please try again! Error Code was: '.$_FILES['Logo']['error'].'</div>';
}
}
?>
It always goes to the "else" statement on that code, I have an uploads folder in the same directory as this php file set to 777 file permissions. The image I am test uploading is under 10KB in size. But the move_uploaded_file() always fails and it doesn't return any error message except for the custom error message made with the else statement.
You're referring to the file in the $_FILES array by two different names -
$Logo = $_FILES['Logo']['name'];
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)
Which one is it? Logo or uploadedfile ?
You're probably referencing an array index which doesn't exist.
Possible reasons:
The uploading of the file failed in some way.
You don't have permission to move the file to the target path.
As PHP.NET says:
If filename is not a valid upload file, then no action will occur, and
move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some
reason, no action will occur, and move_uploaded_file() will return
FALSE. Additionally, a warning will be issued.
Reference: http://php.net/manual/en/function.move-uploaded-file.php

Categories