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);
?>
Related
<body>
<form action="#" enctype="multipart/form-data" method="post">
<input multiple="" name="img[]" type="file" />
<input name="submit" type="submit" />
</form>
<?php
mmysql_connect("localhost","root","");
mysql_select_db("multiple");
if(isset($_POST['submit'])){
$filename = $_FILES['img']['name']);
$tmpname = $_FILES['img']['tmp_name']
$filetype = $_FILES['img']['type'];
for($i=0; $i<=count($tmpname)-1; $i++){
$name =addslashes(filename[$i]);
$tmp = addslashes(file_get_contents($tmpname[$i]));
mysql_query("INSERT into img(name,image) values('$name','$tmp')");
echo "uploaded";
}
}
?>
</body>
</html>
I am trying to upload a simple image to my database So I can work on this user hosted site. So far nothing has worked. I'm dyin here. I've looked through so many tutorials.
From hitting an issue with file uploads before, it's much easier on the DB and your coding to upload your file to the server using 'move_uploaded_file()' and then provide a reference in your DB. In the above example, you are storing your file in a temporary folder ['tmp_name'], saving that file name, but then not transferring the file somewhere that won't delete it.
So for something generic to help:
$fileName $_FILES['img']['name'];
$fileType = $_FILES['img']['type'];
$fileLocation = $_FILES['img']['tmp_name'];
$newFileName = "newFileName.jpg";
$img = "folder/".$newFileName;
move_uploaded_file($fileLocation, "../folder/".$newFileName);
The reason for this is that when you save to the 'tmp' folder (which you must for a bit), the file is also renamed to a seemingly random set of characters. So you need to get that file location, move it to the folder of your choice, and also name it something findable. Then you can save the $img path in your DB and call it from anywhere (with some modification). It will take some playing with, but this should help.
To upload an image to the database directly from an uploaded file, you need to upload the base64 encoded version of the image. And also make sure that the field type of the image in your database is actually blog or LongBlog.
Here is the code to do that
$file = $_FILES['file'];
$filename = $file['name'];
$convert_to_base64 = base64_encode(file_get_contents($file['tmp_name']));
$base64_image = "data:image/jpeg;base64,".$convert_to_base64;
$query = mysqli_query($con, "INSERT INTO 'table'(image)VALUES('$base64_image')")
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
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');
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/
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')");