Upload images using php - php

I have a an input type file which is hidden and triggered using another button .. the input must upload images only to a folder named Covers but the code is not working and not uploading any image..
html code
<div class="cover">
<img src="Layout/images/cover.jpg" alt="cover" name="cover-img" class="cover-img">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" enctype="multipart/form-data">
<button type="submit" name="submit-cover" id="cover-btn">Change Cover</button>
<input type="file" name="avatar" id="cover-img-input" class="hidden" />
</form>
php codes:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['submit-cover'])) {
$avatarName = $_FILES['avatar']['name'];
$avatarTempName = $_FILES['avatar']['tmp_name'];
// List of allowed image extensions
$avatarAllowedExtensions = array("jpeg","jpg","png","gif");
// Get avatar extension
$avatarExtension = strtolower(end(explode('.',$avatarName)));
// Check if uploaded image extension is in allowed image extensions
$formErrors=array();
if(! empty($avatarName) && ! in_array($avatarExtension, $avatarAllowedExtensions)) {
$formErrors[]='This extension is <strong>not allowed</strong>';
}
if(empty($avatarName)) {
$formErrors[]='No image <strong>uploaded</strong>';
}
if(empty($formErrors)) {
// Create random number between zero to million to concatinate it with image name
$avatar = rand(0,1000000) . '_' . $avatarName;
// Move image into Covers folder
move_uploaded_file($avatarTempName, "Uploads\Covers\\" . $avatar);
}
}
}
I get
Fatal error: Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' in D:\XAMPP\htdocs\Warina\connect.php on line 7
after that I searched for a solution and get this: extension=php_pdo_mysql.dll should be uncommented in my php.ini and it is uncommented now I'm confused about this error too.

This line sends a notice:
$avatarExtension = strtolower(end(explode('.',$avatarName)));
Notice: Only variables should be passed by reference in file.php on line xx
Replace with
$avatarExtension = explode('.',$avatarName);
$avatarExtension = strtolower(end($avatarExtension));
Fix this path:
move_uploaded_file($avatarTempName, "Uploads\Covers\\" . $avatar);
With
move_uploaded_file($avatarTempName, "Uploads\\Covers\\" . $avatar);
And make sure it exists

Related

Uploading File from Custom Form HTML

I'm trying to upload a file from my custom HTML form to a PHP script. Here is the code that I have in my HTML.
<form action="test.php" method="post" enctype="multipart/form-data">
<input id="txt" class="button" type = "text" value = "Choose File" onclick ="javascript:document.getElementById('file').click();">
<input id = "file" type="file" style='visibility: hidden;' name="img" onchange="ChangeText(this, 'txt');"/>
<input type="submit">
</form>
Here is the test.php file:
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$target = "i/";
if (move_uploaded_file($_FILES['img']['tmp_name'], $target)) {
echo "The file " . basename($_FILES['img']['name']) . "has been uploaded";
}
Here's the error on the page:
Warning: move_uploaded_file(): The second argument to copy() function cannot be a directory in /var/www/BLOCKED/test.php on line 7
Warning: move_uploaded_file(): Unable to move '/tmp/phpNxxB72' to 'i/' in /var/www/BLOCKED/test.php on line 7.
Yes it's permissions of the directory are 777.
the 2nd argument of move_uploaded_file should be a file name (with path) not a directory
$target = "i/".basename($_FILES['img']['name']);
The error is correct. The 2nd parameter to move_uploaded_file() is not a directory, it should be a file. You just need to append the file's name to $target in the 2nd parameter. For example:
if (move_uploaded_file($_FILES['img']['tmp_name'], $target.$_FILES['img']['name'])) {
echo "The file " . basename($_FILES['img']['name']) . "has been uploaded";
}
move_uploaded_file function should be like this:
move_uploaded_file($_FILES['img']['tmp_name'], $target. $_FILES["img"]["name"])
add file name at end, as $target is a directory/folder only.
Tantibus, as you can read here:
http://php.net/manual/en/function.move-uploaded-file.php
You must specify the file name to your target file.
$target = "i/".basename($_FILES['img']['name']);
you probably missed this.

Warning: getimagesize() [function.getimagesize]: Filename cannot be empty warning message?

Up until recently I've been using some PHP to upload photos to a site. But suddenly it's started triggering all sorts of error messages.
I use a form that on action runs the following code:
$uploaddir = "../../user_content/photo/";
$allowed_ext = array("jpeg", "jpg", "gif", "png");
if(isset($_POST["submit"])) {
$file_temp = $_FILES['file']['tmp_name'];
$info = getimagesize($file_temp);
} else {
print "File not sent to server succesfully!";
exit;
}
The file upload part of the form has the following elements:
<input name="file" type="file" class="photo_file_upload">
The submit button for uploading has the following attributes:
<button type="submit" name="submit" class="photo_upload">Upload</button>
But whenever I run this, I always get the following warning:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in (upload PHP file) on line 10
(line 10 is this part: $info = getimagesize($file_temp);)
Anyone have any ideas on what the cause of this is?
You checked if the form was submitted, but didn't check if the file was sent. In some cases, a form could be submitted but the file will not sent (i.e. file size is bigger then file size limit in config).
Use this:
if(isset($_POST["submit"]) && isset($_FILES['file'])) {
$file_temp = $_FILES['file']['tmp_name'];
$info = getimagesize($file_temp);
} else {
print "File not sent to server succesfully!";
exit;
}
You see && isset($_FILES['file']) is new
Or you can extend it
if(isset($_POST["submit"]) && isset($_FILES['file'])) {
$file_temp = $_FILES['file']['tmp_name'];
$info = getimagesize($file_temp);
}
elseif(isset($_POST["submit"]) && !isset($_FILES['file'])) {
print "Form was submitted but file wasn't send";
exit;
}
else {
print "Form wasn't submitted!";
exit;
}
Change these parameters in your php.ini file; (Currently it allow only 2Mb size to
upload and post). Sometimes it's reason for these errors.
upload_max_filesize = 500M
post_max_size = 500M
max_execution_time = 120
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in
Verify the MAX_SIZE variable,
example to define it for a 2Mo image:
define('MAX_SIZE', 2000000);
<form enctype="multipart/form-data" method="post" action="upload.php">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_SIZE; ?>" />
<input name="fichier" type="file" id="fichier_a_uploader" /> <br>
<input type="submit" name="submit" value="Uploader" />
</form>
you can also verify the Maximum size of POST data that PHP will accept and Maximum allowed size for uploaded files in PHP.ini :
post_max_size = ?
upload_max_filesize = ?
After you upgrade 'upload-max-filesize' , Restart all Services of wamp or xampp ! it will right !
you should change the form enctype to "multipart/form-data"
<form method="post" enctype="multipart/form-data">
....
</form>
Notice: Undefined index: fileToUpload in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 38
Notice: Undefined index: fileToUpload in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 43
Warning: getimagesize(): Filename cannot be empty in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 43
File is not an image.Sorry, file already exists.
Notice: Undefined index: fileToUpload in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 58
Sorry, only JPG, JPEG, PNG & GIF files are allowed.Sorry, your file was not uploaded.
If You Get Errors like this one you should check you have added form enctype to "multipart/form-data"
<form method="post" enctype="multipart/form-data">
....
</form>
Use to catch me out quite a lot to begin with.

Upload script in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Unable to do File Upload in PHP
I am trying to learn to write file upload script in PHP. I don't know why this doesn't work. Please have a look
<?php
$name=$_FILES["file"]["name"];
if(isset($name)) {
if(!empty($name)) {
echo $name;
}
else {
echo 'Please choose a file';
}
}
?>
It gives an error message Notice: Undefined index: file in
The html part is
<form action="submissions.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" /></form>
I am using wamp on Windows. What may be the cause for the error ?
You need to check if the form was submitted before executing your PHP code:
<?php
if (isset($_POST["submit"]) && $_POST["submit"] === "Submit") {
if (isset($_FILES["file"]["name"])) {
$name = $_FILES["file"]["name"];
if(!empty($name)) {
echo $name;
}
else {
echo 'Please choose a file';
}
}
}
?>
The clue is in the error message. The index 'file' doesn't exist in the FILES array. At a guess because you have this code before you've sumitted the form?
check if it exists first,
if(isset($_FILES['FormFieldNameForFile']) && $_FILES['FormFieldNameForFile']['size']>0){ # will be 0 if no file uploaded
then check your use of the field components.
$_FILES['userfile']['name'] # The original name of the file on the client machine.
$_FILES['userfile']['type'] # The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['userfile']['size'] # The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name'] # The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error'] # The error code associated with this file upload

Download image from URL using php code? [duplicate]

This question already has answers here:
Saving image from PHP URL
(11 answers)
Closed 6 years ago.
How can I use php to download an image from URL (eg: https://www.google.com/images/srpr/logo3w.png) then save it?
This is what I came up with so far, it gives me an error in 'file_put_contents' function.
<form method="post" action="">
<textarea name="text" cols="60" rows="10">
</textarea><br/>
<input type="submit" class="button" value="submit" />
</form>
<?php
$img = "no image";
if (isset($_POST['text']))
{
$content = file_get_contents($_POST['text']);
$img_path = '/images/';
file_put_contents($img_path, $content);
$img = "<img src=\"".$img_path."\"/>";
}
echo $img;
?>
It gives me the error:
[function.file-put-contents]: failed to open stream: No such file or directory in C:\wamp\www\img.php
The /images/ directory is located in the same directory of the php file and is writable.
You cannot save the image with your existing code because you do not provide a file name. You need to do something like:
$filenameIn = $_POST['text'];
$filenameOut = __DIR__ . '/images/' . basename($_POST['text']);
$contentOrFalseOnFailure = file_get_contents($filenameIn);
$byteCountOrFalseOnFailure = file_put_contents($filenameOut, $contentOrFalseOnFailure);
file_put_contents() requires first parameter to be file name not the path.
What is your error ? But you have the right way to do what you want to do.
Just take care in your code, I can see file_put_contents($img_path, but $img_path is a path to a folder.
You need to write something like :
example
$img_path="home/downloads/my_images";
file_put_contents($img_path."/flower.jpg");
file_put_contents($img_path, $content);
To what are you putting to?? i think you have made a mistake with get and put. or missed to specify the full path including the file name and extension
I added one condition to accepted answer to check the image type as follows,
if (exif_imagetype($_POST['text']) == IMAGETYPE_PNG) {
$filename = './images/'.basename($_POST['text']);
file_put_contents($filename, $content);
}
from above example I show how to check png images before download the files and for more content types you can find here .

PHP code breaking HTML layout

I have a simple file uploader, which thanks to stackoverflow is now fully working, however when I copied the PHP code across to my main layout, once initialised to upload a file, but it is wrong format or size and it echos the error, it breaks the HTML below it. Im thinking its to do with the "exit;" after each echo? but could be wrong.
<?php
if($_POST['upload']) {
if($_FILES['image']['name'] == "")
{
#there's no file name return an error
echo "<br/><b>Please select a file to upload!\n</b>";
exit;
}
#we have a filename, continue
#directory to upload to
$uploads = '/home/habbonow/public_html/other/quacked/photos';
$usruploads = 'photos';
#allowed file types
$type_array = array(image_type_to_mime_type(IMAGETYPE_JPEG), image_type_to_mime_type(IMAGETYPE_GIF), image_type_to_mime_type(IMAGETYPE_PNG), 'image/pjpeg');
if(!in_array($_FILES['image']['type'], $type_array))
{
#the type of the file is not in the list we want to allow
echo "<br/><b>That file type is not allowed!\n</b>";
exit;
}
$max_filesize = 512000;
$max_filesize_kb = ($max_filesize / 1024);
if($_FILES['image']['size'] > $max_filesize)
{
#file is larger than the value of $max_filesize return an error
echo "<br/><b>Your file is too large, files may be up to ".$max_filesize_kb."kb\n</b>";
exit;
}
$imagesize = getimagesize($_FILES['image']['tmp_name']);
#get width
$imagewidth = $imagesize[0];
#get height
$imageheight = $imagesize[1];
#allowed dimensions
$maxwidth = 1024;
$maxheight = 1024;
if($imagewidth > $maxwidth || $imageheight > $maxheight)
{
#one or both of the image dimensions are larger than the allowed sizes return an error
echo "<br/><b>Your file is too large, files may be up to ".$maxwidth."px x ".$maxheight."px in size\n</b>";
exit;
}
move_uploaded_file($_FILES['image']['tmp_name'], $uploads.'/'.$_FILES['image']['name']) or die ("Couldn't upload ".$_FILES['image']['name']." \n");
echo "<br/>The URL to your photo is <b>" . $usruploads . "/" . $_FILES['image']['name'] . "</b>. Please use this when defining the gallery photos";
}
?>
<form name="uploader" method="post" action="" enctype="multipart/form-data">
<input type="file" name="image" style="width:300px;cursor:pointer" />
<input type="submit" name="upload" value="Upload Image" />
</form>
Indeed, when you call exit; it means "immediately stop all processing; this script is finished." Anything that comes after it — including HTML — will not be interpreted.
A better organization would be to make this code a function, to the effect of:
function uploadMyStuffPlease() {
if($_POST['upload']) {
if($_FILES['image']['name'] == "")
{
#there's no file name return an error
echo "<br/><b>Please select a file to upload!\n</b>";
return;
}
#we have a filename, continue
// ....
}
Now you can simply call uploadMyStuffPlease(), which will do as much processing as it can, and perhaps return early in the event of an error. Either way, the function will return, and so the rest of your script (including that HTML) can still be interpreted.
If you call exit; your PHP script won't be able to output anything anymore. That's why the layout is broken.
You should maybe try to keep the HTML parts out of your PHP code and especially avoid opening tags that you don't close afterwards (i.e. divs or anything).
That being said, it's probably safest to just put everything into a function that won't exit the script when finished (see other's posts).
if(isset($_POST['upload'])){
OR
if(!empty($_POST['upload'])){
And remove exit...

Categories