Upload image to existing folder PHP - php

<?php
include('includes/db.php');
$drinks_cat = $_POST['drinks_cat'];
$drinks_name = $_POST['drinks_name'];
$drinks_shot = $_POST['drinks_shot'];
$drinks_bottle = $_POST['drinks_bottle'];
$drinks_availability = 'AVAILABLE';
$msg = "ERROR: ";
$itemimageload="true";
$itemimage_size=$_FILES['image']['size'];
$iname = $_FILES['image']['name'];
if ($_FILES['image']['size']>250000){$msg=$msg."Your uploaded file size is more than 250KB so please reduce the file size and then upload.<BR>";
$itemimageload="false";}
if (!($_FILES['image']['type'] =="image/jpeg" OR $_FILES['image']['type'] =="image/gif" OR $_FILES['image']['type'] =="image/png"))
{$msg=$msg."Your uploaded file must be of JPG , PNG or GIF. Other file types are not allowed<BR>";
$itemimageload="false";}
$file_name=$_FILES['image']['name'];
$add="images"; // the path with the file name where the file will be stored
if($itemimageload=="true")
{
if (file_exists($add) && is_writable($add))
{
if(move_uploaded_file ($_FILES['image']['tmp_name'], $add."/".$_FILES['image']['name']))
{
echo "Image successfully updated!";
}
else
{
echo "Failed to upload file Contact Site admin to fix the problem";
}
}
else
{
echo 'Upload directory is not writable, or does not exist.';
}
}
else
{
echo $msg;
}
$dir = $add."/".$iname;
echo "<BR>";
// Connects to your Database
mysql_query("INSERT INTO `product_drinks`(`drinks_id`, `drinks_cat`, `drinks_name`, `drinks_shot`, `drinks_bottle`, `drinks_image`, `drinks_availability`) VALUES (NULL,'".$drinks_cat."', '".$drinks_name."','".$drinks_shot."','".$drinks_bottle."','".$dir."','".$drinks_availability."')") or die("insert error");
Print "Your table has been populated";
?>
The code I'm working on works but i have to create a new "image" folder for my admin folder. Is there any way that I could upload the file outside the admin folder and move it to to the original "image" folder". I know it's quite confusing but my directory looks like this.
clubmaru
-admin
-images
-css
-images
-js

You may be looking for PHP's rename function. http://php.net/manual/en/function.rename.php
Set the oldname parameter to the file (with its path) and the newname parameter to where you want it to be (along with the new path, obviously)
Just ensure the "image folder" you want to move the file to has the correct permissions set ensure it's writable. You also may want to consider changing the parameter in your move_uploaded_file to put the file where you want it in the first place!

Yes there is a way, you need to change the path. Right now you have the path as images/$name which means that it will put the file in the images directory found in the local directory to the script that is running.
Using directory layout:
clubmaru
->admin
->script.php (the upload file)
->images
->css
->images
->js
You make the path relative (or find another alternative)
$add="../css/images";
This means, go up a directory, go into css then into images.

Related

Warning : file_put_contents() failed to open stream : No such file or directory

I am trying to upload an image from android to mysql
Now the path can be successfully uploaded but there's something wrong on this code
<?php
require_once '../database/database.php';
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
// base_64 encoded string from android
$imageData = $_POST['image'];
// edittext from android
// $imageName = $_POST['image_name'];
$path = "images/Sample.jpg";
$actualPath = "http://192.168.254.123/*****/admin/$path";
if($user->UploadFiles($actualPath))
{
file_put_contents($path, base64_decode($imageData));
echo "Success";
}
else
{
echo "Failed";
}
}
?>
On the line where file_put_content is the error . here's the full error
Warning file_put_contents(images/Sample.jpg):failed to open stream:No such file or directory in C:\xampp\htdocs\projectname\admin\apk_api\upload_profile.php on line 17
Here's the proof that I can actually save the path on my database
and here's my directory
Can someone please help me out.
The directory images/ does not exists from the point of view, where the admin\apk_api\upload_profile.php file is. The resulting directory path will be
C:\xampp\htdocs\projectname\admin\apk_api\images\
However, the target directory should be
C:\xampp\htdocs\projectname\admin\images\
Create a relative path based from the location of the admin\apk_api\upload_profile.php file. You have to use something like ../images/ to get to the target directory.

upload image on a parallel directory's folder

I have two directories:
/publichtml
/csp.example.com
My code is in csp.example.com/classes/ep-class.php and I want to upload my file on /publichtml/upload/photo folder. How can I achieve that also /publichtml is accessible using example.com so I am taking target directory as a absolute url?
Here is my code:
if(isset($_FILES["imagefile"]["type"][0]))
{
$filename=$_FILES["imagefile"]["name"][0];
// Storing source path of the file in a variable
$sourcePath = $_FILES['imagefile']['tmp_name'][0];
// Target path where file is to be stored
$targetPath = SITEURL."upload/photo/".$filename;
if(move_uploaded_file($sourcePath,$targetPath))
{
return "Yes";
}
else
{
echo $_FILES["imagefile"]["errors"][0];
die("File upload error !");
}
}
Any help would be highly appreciated.

Image upload to mysql

My site is able to upload a file but I don't understand how to get the path to the file for the database query. When someone uploads an image, the path to the image should get directly inserted into the users table in the userpic field. How can I achieve this?
<?PHP
if(isset($_FILES['file'])) {
move_uploaded_file($_FILES['file']['tmp_name'],'files/'.$_FILES['file']['name']);
session_start();
$username = $_SESSION['user'];
$userpic = ???? // <-- what am i supposed to call here to put the path to my image file
include ("connect.php");
$sql = $con->prepare('INSERT INTO users (username,userpic) VALUES (?,?)');
$sql->bind_param("ss",$username,$userpic);
$sql->execute();
$sql->close();
$con->close();
} else {
echo "no files";
}
?>
If you store files using the name provided by the client when the file is uploaded, you will potentially overwrite images (e.g. if two users upload me.png) - it would be much better to use the username to store the images, and then you don't even need the mysql table to connect users to their pics..
<?php
session_start();
$username = $_SESSION['user'];
if(empty($username)){
echo "Error: no username found";
}
else if(isset($_FILES['file']) ){
//create a path to move file to
$newpath = 'files/'.$username;
if (move_uploaded_file($_FILES['file']['tmp_name'], $newpath)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Error: Possible file upload attack!\n";
}
}
else{
echo "No Files to save";
}
In this code we use the username from the session, and check its not blank.
We then use this to store the image in your files folder.
Note this ignores a number of security issues:
Including ../ in your username which would cause the file to be saved outside of the files directory.
This may not be an issue if you have already validated the username, another solution would be to create a hash of the username and using this instead: $newpath = 'files/'.md5($username);
Not checking for errors, or verifying the file is indeed an image.
http://php.net/manual/en/features.file-upload.errors.php
PHP image upload security check list
How are these images going to be used after this?
If the files directory is within your htdocs, the contents will be available for all - it would probably be better to store it outside of your htdocs
e.g. $newpath = '/var/myappdata/userimages/'.md5($username);
You could then create another file userimage.php which reads the file:
<?php
session_start();
$username = $_SESSION['user'];
$path = '/var/myappdata/userimages/'.md5($username);
readfile($path);
This allows you to do additional checks e.g. that the user is allowed to see the image.
There is still a huge amount that could be covered here, hopefully this gives you enough to move forward, but do please read more about file upload security before putting this into production.
Your original question
If you did want to store information about the image in your database you could do something like this:
<?php
session_start();
include ("connect.php");
$username = $_SESSION['user'];
if(empty($username)){
echo "Error: no username found";
}
else if(isset($_FILES['file']) ){
//create a path to move file to
$filename = basename($_FILES['file']['name']);
$newpath = 'files/'.$filename;
if (move_uploaded_file($_FILES['file']['tmp_name'], $newpath)) {
echo "File is valid, and was successfully uploaded.\n";
$sql = $con->prepare('INSERT INTO users (username,userpic) VALUES (?,?)');
$sql->bind_param("ss",$username,$filename);
$sql->execute();
$sql->close();
$con->close();
} else {
echo "Error: Possible file upload attack!\n";
}
}
else{
echo "No Files to save";
}
As I said though - you will run into conflicts if two users upload the same file.
You aren't going to want to store the entire URL in the database. You just need the path to where it is on the server. That is the part where you are moving the tmp file to a new location. In your case it would be the following.
$userpic = 'files/'.$_FILES['file']['name'];

not able to upload files in specific directory

i have made a small image uploading system using php it was working fine but now when i tried to upload pics in a specific folder then it is giving errors and upload images in root folder only.
the php code is:
<?php
//checking if the user already has a directory or not.
if($r['directory']==0){
$query= "UPDATE user SET directory='1' where id='".$_SESSION['sess_id']."'";
mysqli_query($dbconn,$query);
$path='../akshay/work/'.$r['username'];
mkdir($path) or die("unable to create folder");
} if(isset($_POST['submit'])&& $r['directory']==1){
//uploading users work.
$path='../akshay/work/'.$r['username'];
$name=$_FILES['work']['name'];
$size=$_FILES['work']['size'];
$type=$_FILES['work']['type'];
$tmp_name=$_FILES['work']['tmp_name'];
$extension=strtolower(substr($name,strpos($name,'.') + 1));
//checking if the user has selected a file or not.
if(isset($name)){
if(!empty($name)){
//checking if the uploaded file is an image or not.
if($extension=='jpg'||$extension=='jpeg'&& $type=='image/jpeg'){
$location=$path;
if(move_uploaded_file($tmp_name,$location.$name)){
echo'uploaded succesfully';
}else{
echo'<p style=color:red;>please choose a file</p>';
}
} else {
echo'<p style=color:red;>format of the file must be jpg/jpeg</p>';
}
}
}
}
?>
i think the problem is in move_uploaded_file() function. plz help me fix this problem and please do tell me any other ways (if any) to do this. i am able to make directories using the first check.
the error is "undefined variable:dir_name "and prints the massage "uploaded succesfully".
i have did some editing in the code and now i am able to make a directory in the specified location but cant upload images in that folder instead it uploads the images in 'work' folder and with the username appended to the name of the image.
please help!!!
In else if part of your code, $dir_name is not defined.
So please update your code and add below:
else if(isset($_POST['submit'])&& $r['directory']==1){
$dir_name = $r['username'];
// your code continue..
Furthermore.. the code you are using is not good. as if if condition is true then the else if part will not be executed. so update your code as below:
<?php
//checking if the user already has a directory or not.
if($r['directory']==0){
$query= "UPDATE user SET directory='1' where id='".$_SESSION['sess_id']."'";
mysqli_query($dbconn,$query);
$dir_name=$r['username'];
$r['directory']=1;
mkdir($dir_name);
}
if(isset($_POST['submit'])&& $r['directory']==1){
$dir_name = $r['username'];
//uploading users work.
$name=$_FILES['work']['name'];
$size=$_FILES['work']['size'];
$type=$_FILES['work']['type'];
$tmp_name=$_FILES['work']['tmp_name'];
$extension=strtolower(substr($name,strpos($name,'.') + 1));
//checking if the user has selected a file or not.
if(isset($name)){
if(!empty($name)){
//checking if the uploaded file is an image or not.
if($extension=='jpg'||$extension=='jpeg'&& $type=='image/jpeg'){
if(move_uploaded_file($tmp_name,$dir_name.$name)){
echo'uploaded succesfully';
}else{
echo'<p style=color:red;>please choose a file</p>';
}
}
else
{
echo'<p style=color:red;>format of the file must be jpg/jpeg</p>';
}
}
}
}
?>
use this code ..
$directory ="../images/".$file_name;
move_uploaded_file($temp_name, $directory);
i think this will work for you

PHP can't upload files to server?

I have a php file that uploads images like jpegs and png onto a folder called uploads that is stored on the apache server and in the same location as the php file.
I have checked the code of both the HTML and the PHP and both seem to be perfectly fine, however whenever I try to upload a file I always get an error message and the file doesn't get uploaded.
It would be much appreciated if someone with more experience than me can look at my code and tell me why it is behaving in this manner.
Here is the HTML form:
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Your File</title>
</head>
<body>
<?php
// put your code here
?>
<form enctype="multipart/form-data" method="post" action="fileHandler.php">
Select File:
<input name="uploaded_file" type="file"/><br/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
and here is the PHP file that is executed when the form is submitted:
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
* PHP file that uploads files and handles any errors that may occur
* when the file is being uploaded. Then places that file into the
* "uploads" directory. File cannot work is no "uploads" directory is created in the
* same directory as the function.
*/
$fileName = $_FILES["uploaded_file"]["name"];//the files name takes from the HTML form
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"];//file in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"];//the type of file
$fileSize = $_FILES["uploaded_file"]["size"];//file size in bytes
$fileErrorMsg = $FILES["uploaded_file"]["error"];//0 for false and 1 for true
$target_path = "uploads/" . basename( $_FILES["uploaded_file"]["name"]);
echo "file name: $fileName </br> temp file location: $fileTmpLoc<br/> file type: $fileType<br/> file size: $fileSize<br/> file upload target: $target_path<br/> file error msg: $fileErrorMsg<br/>";
//START PHP Image Upload Error Handling---------------------------------------------------------------------------------------------------
if(!$fileTmpLoc)//no file was chosen ie file = null
{
echo "ERROR: Please select a file before clicking submit button.";
exit();
}
else
if(!$fileSize > 16777215)//if file is > 16MB (Max size of MEDIUMBLOB)
{
echo "ERROR: Your file was larger than 16 Megabytes";
unlink($fileTmpLoc);//remove the uploaded file from the PHP folder
exit();
}
else
if(!preg_match("/\.(gif|jpg|jpeg|png)$/i", $fileName))//this codition allows only the type of files listed to be uploaded
{
echo "ERROR: Your image was not .gif, .jpg, .jpeg or .png";
unlink($fileTmpLoc);//remove the uploaded file from the PHP temp folder
exit();
}
else
if($fileErrorMsg == 1)//if file uploaded error key = 1 ie is true
{
echo "ERROR: An error occured while processing the file. Please try again.";
exit();
}
//END PHP Image Upload Error Handling---------------------------------------------------------------------------------------------------------------------
//Place it into your "uploads" folder using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, $target_path);
//Check to make sure the result is true before continuing
if($moveResult != true)
{
echo "ERROR: File not uploaded. Please Try again.";
unlink($fileTmpLoc);//remove the uploaded file from the PHP temp folder
}
else
{
//Display to the page so you see what is happening
echo "The file named <strong>$fileName</strong> uploaded successfully.<br/><br/>";
echo "It is <strong>$fileSize</strong> bytes.<br/><br/>";
echo "It is a <strong>$fileType</strong> type of file.<br/><br/>";
echo "The Error Message output for this upload is: $fileErrorMsg";
}
?>
make sure that the directory structure has write permissions. You can check within php by using is_writeable. By checking from within PHP you will also be making sure that the PHP user has write access.
Check the folder permissions on the server. If incorrect, you can modify your php.ini file.

Categories