PHP imagejpeg doesn't work - php

So I looked almost every question and tried to work to show my image using the php script below. But it doesn't work. I also tried to see if GD library is enabled with PHPInfo() and it is working as well. I am very new to PHP but can't seem to get this working. Thanks for your help!
EDIT: I get a broken image icon after I click on upload a doc button.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_FILES['photo'])
&& is_uploaded_file($_FILES['photo']['tmp_name'])
&& $_FILES['photo']['error'] == UPLOAD_ERR_OK) {
foreach ($_FILES['photo'] as $key => $value) {
echo "$key : $value<br />";
}
if($_FILES['photo']['type'] == 'image/jpeg') {
$tmp_img = $_FILES['photo']['tmp_name'];
$image = imagecreatefromjpeg($tmp_img);
header('Content-Type: image/jpeg');
imagejpeg($image,NULL);
imagedestroy($image);
} else {
echo "Uploaded file ewas not a jpg image.";
}
echo "no photo uploaded.";
}
}
?>
<form enctype="multipart/form-data" action="book.php" method="post">
<input type="file" name="photo">
<input type="submit" value="upload a doc">
</form>

You can try add die(); after imagedestroy($image); to prevent any other output except image data. Also change imagejpeg($image,NULL); to imagejpeg($image);.

You cannot access to image direcly with tmp_name. Firstly you should save the image to the server and after that you can use with imagecreatefromjpeg
<?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'];
$uniq_name = uniqid().".".explode(".",$tmp_img)[1];
move_uploaded_file($_FILES['photo']['tmp_name'],$uniq_name);
$image = imagecreatefromjpeg($uniq_name);
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
} else {
echo "Uploaded file ewas not a jpg image.";
}
echo "no photo uploaded.";
}
}
?>
<form enctype="multipart/form-data" action="book.php" method="post">
<input type="file" name="photo">
<input type="submit" value="upload a doc">
</form>

I think the problem lies with the echo and the output strings after the PHP section (HTML code). Remove the foreach loop and output HTML only if it is a new page or if something is wrong.
<?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,NULL);
imagedestroy($image);
exit; // Add this to stop the program here.
} else {
echo "Uploaded file was not a jpg image.";
}
} else {
echo 'No file was sent.';
}
}
?>
<form enctype="multipart/form-data" action="book.php" method="post">
<input type="file" name="photo">
<input type="submit" value="upload a doc">
</form>
And one other thing, if you code using Notepad, be sure that there are no hidden characters at the beginning of your file.

Related

Warning: Invalid argument supplied for foreach() - uploading photos form

Hi I'm new to php and keep getting this error: "Warning: Invalid argument supplied for foreach() in /home/site/folder/upload.php on line 61."
I'm trying to build a form in which users can upload one or more photos automatically to a directory to then be displayed else where.
Whenever I use this form I created it functions properly on my website but unfortunately it keeps printing that error out and would like it to go away. Here is my code I'm working with:
<div>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="images[]" multiple="multiple"/>
<input type="submit" name="submit" value="upload images"/>
<form/>
<?php
// check if uploads directory exists
$dir = "images/";
if(!is_dir($dir))
{
echo "Directory not found, let's create the folder.";
mkdir($dir,"0777", true);
}
$countimg = 0;
$allimg = 0;
foreach($_FILES["images"]["name"] as $k=>$name)
{
$allimg++;
$imgname = $_FILES["images"]["name"][$k];
$sizeimg = $_FILES["images"]["size"][$k];
$tmpname = $_FILES["images"]["tmp_name"][$k];
//2.
$extension = strtolower(pathinfo($dir.$imgname, PATHINFO_EXTENSION));
if($extension=='png' || $extension=='jpg' ||$extension=='jpeg' ||$extension=='gif')
{
if($sizeimg < 2097152){
if(!file_exists($dir.$imgname)){
//1.
if(move_uploaded_file($tmpname,$dir.$imgname))
{
$countimg++;
}
}
}
}
}
echo "You are trying to upload $allimg images".'<br>';
echo "From $allimg image(s) - $countimg was/were uploaded with success".'<br>';
$z = $allimg - $countimg;
echo "$z image(s) were not uploaded: Not an image, over 2MB, or already uploaded.";
?>
</div>
Try
if (count($_FILES)) {
foreach($_FILES["images"]["name"] as $k=>$name) {
....
}
}
I tested your script, it works fine. The error message appears because you are not checking that a file got uploaded before starting the foreach. If I land on the page, the PHP code will still be triggered. To fix this, you may use the below:
<div>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="images[]" multiple="multiple"/>
<input type="submit" name="submit" value="upload images"/>
<form/>
<?php
if( $_POST['submit'] ) {
$dir = "images/";
if(!is_dir($dir))
{
echo "Directory not found, let's create the folder.";
mkdir($dir,"0777", true);
}
$countimg = 0;
$allimg = 0;
foreach($_FILES["images"]["name"] as $k=>$name)
{
$allimg++;
$imgname = $_FILES["images"]["name"][$k];
$sizeimg = $_FILES["images"]["size"][$k];
$tmpname = $_FILES["images"]["tmp_name"][$k];
//2.
$extension = strtolower(pathinfo($dir.$imgname, PATHINFO_EXTENSION));
if($extension=='png' || $extension=='jpg' ||$extension=='jpeg' ||$extension=='gif')
{
if($sizeimg < 2097152){
if(!file_exists($dir.$imgname)){
//1.
if(move_uploaded_file($tmpname,$dir.$imgname))
{
$countimg++;
}
}
}
}
}
echo "You are trying to upload $allimg images".'<br>';
echo "From $allimg image(s) - $countimg was/were uploaded with success".'<br>';
$z = $allimg - $countimg;
echo "$z image(s) were not uploaded: Not an image, over 2MB, or already uploaded.";
}
?>
</div>
if( $_POST['submit'] ) will ensure that the form is submitted prior to running the rest of the PHP code.

uploading video file not working

I want to upload video files in php for that i am using following code
PHP
$newUploadDir = "c://video";
$idx = "file";
if (isset($_FILES[$idx]) && is_array($_FILES[$idx])) {
echo "file set";
foreach ($_FILES[$idx]["error"] as $key => $error) {
echo "loop";
if ($error == UPLOAD_ERR_OK) {
echo "<br/>dd2";
$tmp_name = $_FILES[$idx]["tmp_name"][$key];
$name = $_FILES[$idx]["name"][$key];
$ext1 = explode(".", $name);
$extension = end($ext1);
$newfilename = "test".".".$extension;
$video_types = array('mp4', 'avi','webm');
if (in_array($extension, $video_types)) {
if (move_uploaded_file($tmp_name, $newUploadDir.$newfilename)) {
echo "uploaded to folder";
} else {
echo "Not uploaded to folder";
}
}
} else {
echo "not uploaded $error";
}
}
}
echo "ok";
HTML
<form action="http://localhost/fileupload/video.php" enctype="multipart/form-data" method="post">
<input id="file1" name="file[]" type="file"/>
<input name="userId" type="text" value="2"/>
<input id="Submit" name="submit" type="submit" value="Submit" />
</form>
Output
file setloopnot uploaded 1ok
Video file is not uploading. How to resolve this?
Actually, if you try to upload very large (video) files, probably the upload file size limit will not let you do that. Instead of regular file upload, there are other possibities. For the begining, look at this, this or this.
An other aproach would be to use third party services like Amazon S3, Microsoft Azure, etc.

Unable to upload mp3 file

I have already change php.in config where have set max_size = 256M but it still does not allow me to upload. I dont know where i am going wrong.....i am able to upload image file, pdf file ,documentary file but not mp3. php.in settings didnt work for me...please anybody can guide me. Below is my php code
Thanks in advance!
<?php
//Concept of file upload
if(isset($_POST['submit']))
{
$file = $_FILES['files']['name'];
$type = $_FILES['files']['type'];
$file_tmp = $_FILES['files']['tmp_name'];
$size = $_FILES['files']['size'];
$file_err = $_FILES['files']['error'];
if($size!=null)
{
if($_FILES['files']['size'] <= 10000000 && $_FILES['files']['type'] == "audio/mpeg")
{
$path = "D:/";
$path = $path.basename($file);
if(!is_uploaded_file($file))
{
$flag = move_uploaded_file($file_tmp, $path);
if($flag == true)
{
echo "Moved Success";
}
else
{
echo "Some problem";
}
}
else
{
echo "Already Uploaded";
}
}
else
{
echo "Not audio file";
}
}
else if($size > 10000000)
{
echo "Size exceeded";
}
else if($size == null)
{
echo "Please select a file";
}
else
{
echo "Error".$file_err;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="basic.php" method="post" enctype="multipart/form-data">
<input type="file" name="files"/>
<input type="submit" value="upload" name="submit"/>
</form>
</body>
</html>
If you are trying to upload an mp3 file, the type of the $_FILES must be
&& $_FILES["file"]["type"] == "audio/mp3"
not
&& $_FILES['files']['type'] == "audio/mpeg"

Image - Upload not responding, no access to $_FILES

Here is my file-upload script, and i am getting the following error
Notice: Undefined index: fupload in C:\Users\Tuskar\Desktop\Projekt\htdocs\Project IT-Space\Profile\edit_profile_parse.php on line 8
But according there should not error, because i identified the index. It seems i don't have access to the $_FILES array, because before i got this error ive been getting other similar errors or the programm completely passes the if and goes directly to the else (file not chosen)
I know the script is primitive and includes almost no security, but i just want it to work first before i add other features like max file size or file restriction ... :(
Here is the code i am using.
Upload Picture
<form action="edit_profile_parse.php" method="get" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="999999999"> </input>
<input type="file" name="fupload"> </input>
<input type="submit" name="submit" value="Upload"> </input>
</form>
Here is the php that handles the form
if (isset( $_GET['submit'] ))
{
if (isset($_FILES['fupload'] ))
{
echo "name: ".$_FILES['fupload']['name']." <br> ";
echo "size: ".$_FILES['fupload']['sizw']." <br> ";
echo "type: ".$_FILES['fupload']['type']." <br> ";
if ($_FILES['fupload']['type'] == "image/gif")
{
$source = $_FILES['fupload']['tmp_name'];
$target = "images/" .$_FILES['fupload']['name'];
move_uploaded_file($source, $target) or die ("Error: " .mysql_error());
$size = getImageSize($target);
$imgstr = "<img src=\" '".$target."' \">";
echo $imgstr;
}
else
{
echo "Problem uploading the file ... ";
}
}
else
{
echo "No file chosen !! ";
}
}
else
{
echo "Button not clicked ";
}
You should use form method to POST instead of get.
<form action="edit_profile_parse.php" method="post" enctype="multipart/form-data" >
Make sure your FORM tag has method="POST". GET requests do not support multipart/form-data uploads.
I hope this works:
the form:
<form action="edit_profile_parse.php" method="post" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="999999999"> </input>
<input type="file" name="fupload"> </input>
<input type="submit" name="submit" value="Upload"> </input>
</form>
the php file:
<?php
if($_POST) {
$max_size = mysql_real_escape_string(strip_tags($_POST['MAX_FILE_SIZE']));
$file = $_FILES['fupload']['name'];
if(isset($max_size) && !empty($max_size) && !empty($file)) {
$file_type = $_FILES['fupload']['type'];
$tmp = $_FILES['fupload']['tmp_name'];
$file_size = $_FILES['fupload']['size'];
$allowed_type = array('image/png', 'image/jpg', 'image/jpeg', 'image/gif');
if(in_array($file_type, $allowed_type)) {
if($file_size < $max_size) {
$path = 'images/'.$file;
move_uploaded_file($tmp, $path);
//if you want to store the file in a db use the $path in the query
} else {
echo 'File size: '.$file_size.' is too big';
}
} else {
echo 'File type: '.$file_type.' is not allowed';
}
} else {
echo 'There are empty fields';
}
}
?>
Upload Picture
<form action="edit_profile_parse.php" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="999999999"> </input>
<input type="file" name="fupload"> </input>
<input type="submit" name="submit" value="Upload"> </input>
</form>
PHP file
<?php
if (isset( $_POST['submit'] ))
{
if (isset($_FILES['fupload'] ))
{
echo "name: ".$_FILES['fupload']['name']." <br> ";
echo "size: ".$_FILES['fupload']['size']." <br> ";
echo "type: ".$_FILES['fupload']['type']." <br> ";
if ($_FILES['fupload']['type'] == "image/gif")
{
$source = $_FILES['fupload']['tmp_name'];
$target = "images/" .$_FILES['fupload']['name'];
move_uploaded_file($source, $target) or die ("Error: " .mysql_error());
$size = getImageSize($target);
$imgstr = "<img src=\" '".$target."' \">";
echo $imgstr;
}
else
{
echo "Problem uploading the file ... ";
}
}
else
{
echo "No file chosen !! ";
}
}
else
{
echo "Button not clicked ";
}
?>

How can I save an image from a file input field using PHP & MySQL?

How can I save an image safely from a file input field using PHP & MySQL?
Here is the input file field.
<input type="file" name="pic" id="pic" size="25" />
This is a simple example, it should work.
Although you probably want to add checking for image types, file sizes, etc.
<?php
$image = $_POST['pic'];
//Stores the filename as it was on the client computer.
$imagename = $_FILES['pic']['name'];
//Stores the filetype e.g image/jpeg
$imagetype = $_FILES['pic']['type'];
//Stores any error codes from the upload.
$imageerror = $_FILES['pic']['error'];
//Stores the tempname as it is given by the host when uploaded.
$imagetemp = $_FILES['pic']['tmp_name'];
//The path you wish to upload the image to
$imagePath = "images/";
if(is_uploaded_file($imagetemp)) {
if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {
echo "Sussecfully uploaded your image.";
}
else {
echo "Failed to move your image.";
}
}
else {
echo "Failed to upload your image.";
}
?>
http://php.net/file_upload covers just about everything you need to know.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$tmpFile = $_FILES['pic']['tmp_name'];
$newFile = '/new_location/to/file/'.$_FILES['pic']['name'];
$result = move_uploaded_file($tmpFile, $newFile);
echo $_FILES['pic']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>
<form action="" enctype="multipart/form-data" method="POST>
<input type="file" name="pic" />
<input type="submit" value="Upload" />
</form>

Categories