PHP Upload image then show - php

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

Related

How to Upload images into folder directory on the server using php

I am trying to upload images onto server.
On the Server the folder name:{photo}
I check the permissions on the folder and it currently on 0755.
When I run my php code, I get this error code:
"Error uploading file - check destination is writeable."
The post that was similar to my issues is this: How to upload photo to my hosting server folder directory
but I already have these functions in my code:
Here my php code:
<?php
$filetmp = $_FILES["file_img"]["tmp_name"];
$filename = $_FILES["file_img"]["name"];
$filetype = $_FILES["file_img"]["type"];
$filesize = $_FILES["file_img"]["size"];
$fileinfo = getimagesize($_FILES["file_img"]["tmp_name"]);
$filewidth = $fileinfo[0];
$fileheight = $fileinfo[1];
$filepath = "../photo/".$filename;
$filepath_thumb = "../photo/thumb/".$filename;
if($_POST['btn_upload'])
{
$sPhotoFileName = $filename;
$nPhotoSize = $filesize;
$sTempFileName = $filetmp;
chmod($filepath_thumb,0755);
chmod($filepath,0755);
if(file_exists('photo/' . $_FILES['file_img']['name'])){
die('File with that name already exists.');
}else{
if ($sPhotoFileName) // file uploaded
{ $aFileNameParts = explode(".", $sPhotoFileName);
$sFileExtension = end($aFileNameParts); // part behind last dot
if ($sFileExtension != "jpg"
&& $sFileExtension != "png"
&& $sFileExtension != "gif")
{ die ("Choose a JPG for the photo");
}
}
if($_FILES['file_img']['error'] > 0){
die('An error ocurred when uploading.');
}
if ($nPhotoSize == 0)
{ die ("Sorry. The upload of $sPhotoFileName has failed.
Search a photo smaller than 300K, using the button.");
}
if ($nPhotoSize > 30240000000)
{ die ("Sorry.
The file $sPhotoFileName is larger than 300K.
Advice: reduce the photo using a drawing tool.");
}
// read photo
$oTempFile = fopen($sTempFileName, "r");
$sBinaryPhoto = fread($oTempFile, fileSize($sTempFileName));
// Try to read image
$nOldErrorReporting = error_reporting(E_ALL & ~(E_WARNING)); // ingore warnings
$oSourceImage = imagecreatefromstring($sBinaryPhoto); // try to create image
error_reporting($nOldErrorReporting);
if (!$oSourceImage) // error, image is not a valid jpg
{ die ("Sorry.
It was not possible to read photo $sPhotoFileName.
Choose another photo in JPG format.");
}
}
$nWidth = imagesx($oSourceImage); // get original source image width
$nHeight = imagesy($oSourceImage); // and height
// create small thumbnail
$nDestinationWidth = 80;
$nDestinationHeight = 60;
//$oDestinationImage = imagecreatetruecolor($nDestinationWidth, $nDestinationHeight);
$oDestinationImage = imagecreate($nDestinationWidth, $nDestinationHeight);
/*$oResult = imagecopyresampled(
$oDestinationImage, $oSourceImage,
0, 0, 0, 0,
$nDestinationWidth, $nDestinationHeight,
$nWidth, $nHeight); // resize the image
*/
imagecopyresized($oDestinationImage, $oSourceImage,0, 0, 0, 0,$nDestinationWidth, $nDestinationHeight,$nWidth, $nHeight); // resize the image
ob_start(); // Start capturing stdout.
imageJPEG($oDestinationImage); // As though output to browser.
$sBinaryThumbnail = ob_get_contents(); // the raw jpeg image data.
ob_end_clean(); // Dump the stdout so it does not screw other output.
// attempt insert query execution
$sql = "INSERT INTO UploadImg (img_name, img_path, img_type) VALUES ('$sPhotoFileName', '$filepath', '$filetype')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
if(!move_uploaded_file($_FILES["file_img"]["tmp_name"],"../photo/".$_FILES["file_img"]["name"])){
die('Error uploading file - check destination is writeable.');
echo "Error Code: " .$_FILES["file_img"]["name"] . "<br>";
}else{
$sBinaryThumbnail = addslashes($sBinaryThumbnail);
$oDatabase = $link;
mysqli_select_db("upload", $oDatabase);
$sQuery = "insert into Uploadimg (thumbnail) VALUES ('$sBinaryThumbnail')";
echo $sQuery;
mysqli_query($sQuery, $oDatabase);
die('File uploaded successfully.');
mysqli_close($link);
}
}
?>
Now I read an article say that even if your folder permission setup up to do all three read, write, and executed on all three level. the code still will not be able to read it depending on the settings on the server.
So I am confused and looking for clarification. Please assist me?
You can upload the image by binary data encoded and save the file with the image format on the server.
755 means it is not world writable. You can set it writable and executable with 777.
This is still vulnerable as anyone with access to your server os can write to the folder, so you should probably just make the web server user the owner of the folder and keep the permissions as they are now. If you're running apache, the user is usually www-data or apache.
I figure it out you gotta set the GID and UID permissionsfilepermission
The set group identification GID allows the owner to execute all applications to read, write and pull to the folder.
Same thing with the User identification UID. the problem is the your folder will be wide open for strangers to manipulate it but it works.
My images are uploading into the folder. Tell me what yall think?
First in your php.ini put
file_uploads = On
Next, create an HTML form that allow users to choose the image file they want to upload:
<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">
Make sure that the form uses method="post"
Then use the php code below to upload image
<?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;
}
}
?>

Understanding uploading files

I apologize for the super long post. I'm super noob and I would LOVE to have your help.
I made a file called Upload Pictures and in this file I have four files. First, php.ini with the following code:
file_uploads = On
Second, upload.html:
<!DOCTYPE html>
<html>
<body>
<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>
</body>
</html>
Third, upload.php:
<?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;
}
}
?>
And fourth, I have a folder called uploads, with nothing inside that folder.
My main questions are from the upload.php file. Please correct me if I am incorrect in my understanding.
I understand $target_dir to be the directory in which the files will be stored. Now to the line with &target_file. I understand that $_FILES["fileToUpload"]["name"] returns the name of the file that I am uploading. So if my file name was picture.jpg, it will return picture.jpg.
My question is then, why do I need to call the basename()? Because I thought this function just returns the name of the file. So it's almost like returning the name twice with $_FILES["fileToUpload"]["name"] and basename()?
Also, it has been my experience that having a . and some function after is calling a method from a class. Is that what is happening here $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);? If so, I'm not sure what is actually being stored into $target_file.
Also, switching gears a little bit here, when I pressed the Upload Image button from my html, it takes me to another page. Is there a way to prevent that from happening?
basename returns the actual filename from a path.
In your example basename does not need to be used on the name being retrieved from $_FILES because it will have no associated path to begin with. In an upload script basename may be more traditionally used on tmp_name to remove any temporary folders from the name of the file.
The . is how you concatenate strings (or in this case variables containing strings) in PHP.
In this example, the code is concatenating the directory and the name of the file together into a variable in which it is used to get the extension in the $imageFileType variable using pathinfo.
The form has an action attribute. action="upload.php" so you will be taken to the 'upload.php' page when the form is submitted.
I hope this answers your questions-
actually basename() function for get file name with the extension of file.
so basename function stand for
basename(path,suffix)
Explanation
Parameter | Description
--------------------------
path | Required. Specifies the path to check
suffix | Optional. Specifies a file extension. If the filename has this file extension, the file extension will not show
Ex
<?php
$path = "/testweb/home.php";
//Show filename with file extension
echo basename($path) ."<br/>";
//Show filename without file extension
echo basename($path,".php");
?>
Output will be
home.php
home
php 5 basename() function
and we use . (dot) operator on here, $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
so this will bind $target_dir and basename(). so $target_file knows where is file should be goes exactly.

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/

Photo uploading using php into a Mysql database

i'm currently making a website for my final year university project, which requires a photo upload function. Currently when a user uploads a photo, the photo is stored in a folder in the remote server. I need the images to go into a database and so I was wondering if anyone had any advice as to how to do this and where to place the code to send the uploaded content to the database within the following code, also I need for it to work where when each individual user uploads an image, they are all displayed for all to see, and not as it is currently, where only one image is displayed at a time and when the page is refreshed, the image disappears. Hope that all made sense, any help would be greatly appreciated. Thank you.
<?php include_once("home_start.php"); ?>
<h1>Upload your images here:</h1>
<div id="fileselect" style="border-bottom:thin #000000 solid; border- collapse:collapse">
<form id="frmSimple" action="home.php" method="post" enctype="multipart/form-data">
Select file to upload:
<input type="file" id="filename" name="filename" size="10" /><br />
<input type="submit" id="submit" name="submit" value=" Upload " />
</form>
</div>
<div id="feedback">
<?php
// Determine whether a file was uploaded
if ($_FILES) {
// Put file properties into variables
$name = $_FILES['filename']['name'];
$size = $_FILES['filename']['size'];
$tmp_name = $_FILES['filename']['tmp_name'];
// Determine whether file is png, jpg or other
switch($_FILES['filename']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
//default: ext = ''; break;
}
//validate against file type
// if $ext is empty string (therefore null or false) image is not a jpg or png
if($ext){
// validate against file size
if($size < 1000000){
// Create a safe name for the file and store in a safe location
$n = "$name"; // Could add .$ext to enforce file type
$n = ereg_replace("[^A-Za-z0-9.]","",$n); // Remove all except alphanumeric characters and
$n = strtolower($n); // Convert to lower case (platform independence)
$n = "uploaded_images/$n"; // Add folder to force safe location
move_uploaded_file($tmp_name, $n); // Move to the safe location and give it the safe
echo "<p>Uploaded image '$name' as '$n': </p>";
echo "<img src='$n' />";
}
else echo "<p>'$name' is too big - 50KB max (50000 bytes).</p>";
}
else echo "<p>'$name' is an invalid file - only jpg and png accepted.</p>";
}
else echo "<p>No image has been uploaded.</p>";
?>
</div>
<?php include_once("home_end.php"); ?>
I would highly recommend against it. Instead, stored the photos in a folder and reference their location from the database (i.e. a string pointing to their location on the filesystem).
However, if you're so inclined to store it in the database, you need to:
Get the file contents after upload
Ensure that the contents don't have any characters that would conflict with your SQL (easy solution is to encode it somehow; base64 perhaps?)
Perform your SQL insert
Again - this is a bad idea. Don't do it - save it to the filesystem.
Also, the following line:
move_uploaded_file($tmp_name, $n);
without any checks of file type, or file integrity, makes it trivial to upload a shell to your box.
Once after the file uploaded successfully get the uploaded image path.
$file_type='jpg'; //if you are using more than one type write a switch case
$file_size = filesize($file);
$fp = fopen($file,'r');
$content = fread($fp,$file_size);
$content = addslashes($content); //content is a binary data of the image
fclose($fp);
To save the image in database. Write a insert query with whatever fields you want $file_name, $file_type, $file_size and content. I am assuming you are able to connect to database successfully.
mysql_query("INSERT INTO Images (id,file_name,file_type,file_size,content)
VALUES ('bird', 'jpg',340kb,'binarydata')");

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