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
Related
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'];
I am new for developing.I have opted for php to learn coding.So I might make mistake as I learn by myself, kindly clarify my doubts.
I have problem in uploading files using php to a folder.What I really do is, I upload a file and the file is saved in a folder and the name of the file alone inserted in the database. While uploading the file I do copy the file to another folder which will be used for the editing purpose so that the original file will not be disturbed.Here the problem I get is, the file is uploaded successfully as well as the name too inserted in database. But it take much time to get upload even the size of the file is small.It works good while I test using my local but when I come in real time this issue(slow uploading) I face. What the person incharge in uploading do is, uploading a file and opening a new browser and upload another file. When the new browser is opened the files get uploaded but in the previous browser it is still in process. The code I have written to copy the file to another folder is not executed as the new browser is opened to upload another set of files. I am using xamp cp v3.2.1.To minimize the execution time I have set the default Maximum execution time to 30. But unable to upload file fastly.
Below is my php coding:
<?php
// connect to the database
include('connect-db.php');
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$file_array=($_FILES['file_array']['name']);
// check to make sure both fields are entered
if ($udate == '' || $file_array=='')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($udate, $file_array, $error);
}
else
{
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
if(isset($_FILES['file_array']))
{
$name_arrray=$_FILES['file_array']['name'];
$tmp_name_arrray=$_FILES['file_array']['tmp_name'];
for($i=0;$i <count($tmp_name_arrray); $i++)
{
if(move_uploaded_file($tmp_name_arrray[$i],"test_uploads/".str_replace(' ','',$name_arrray[$i])))
{
// save the data to the database
$j=str_replace(' ','',$name_arrray[$i]);
echo $j;
$udate = mysql_real_escape_string(htmlspecialchars($_POST['udate']));
$provider = mysql_real_escape_string(htmlspecialchars($_POST['provider']));
$existfile=mysql_query("select ubatch_file from batches");
while($existing = mysql_fetch_array( $existfile)) {
if($j==$existing['ubatch_file'])
echo' <script>
function myFunction() {
alert("file already exists");
}
</script>';
}
mysql_query("INSERT IGNORE batches SET udate='$udate', ubatch_file='$j',provider='$provider',privilege='$_SESSION[PRIVILEGE]'")
or die(mysql_error());
echo $name_arrray[$i]."uploaded completed"."<br>";
$src = 'test_uploads';
$dst = 'copy_test_uploads';
$files = glob("test_uploads/*.*");
foreach($files as $file){
$file_to_go = str_replace($src,$dst,$file);
copy($file, $file_to_go);
/* echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Uploaded.\");
window.location = \"uploadbatches1.php\"
</script>";*/
}
} else
{
echo "move_uploaded_file function failed for".$name_array[$i]."<br>";
}
}
}
// once saved, redirect back to the view page
header("Location:uploadbatches1.php");
}
}
?>
It takes much time because, each and everytime all the files are copied to the newfolder. This exceeds the execution time.Only copying the uploaded files makes uploading and copying files fast.
I want to upload images to mysql server using php.
I have created html and sql connectivity but the image upload shows error.
I cant upload the image, it shows error of valid image i.e. you must upload jpeg,bmp,gif; and read/write in directory.
Can any1 help me solving this problem
the php file is
<?php
//Start session
session_start();
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
// Check to see if the type of file uploaded is a valid image type
function valid($file)
{
// This is an array that holds all the valid image MIME types
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");
//echo $file['type'];
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$TARGET_PATH = "image/";
$TARGET_PATH = $TARGET_PATH . basename( $_FILES['image']['name']);
$pimage = $_FILES['image']['name'];
// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!valid($pimage))
{
$_SESSION['ERRMSG_ARR'] = array('You must upload a jpeg, gif, or bmp');
header("Location: admin.php");
exit;
}
// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($TARGET_PATH))
{
$_SESSION['ERRMSG_ARR'] = array('A file with that name already exists');
header("Location: admin.php");
exit;
}
// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($_FILES['image']['tmp_name'], $TARGET_PATH))
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$sql = "insert into people (p_category, p_name, p_quantity, p_desc, p_image) values ('$pcategory', '$pname','$pquantity','pdesc', '" . $pimage['name'] . "')";
$result = mysql_query($sql);
//Check whether the query was successful or not
if($result) {
$_SESSION['ERRMSG_ARR'] = array('Product added');;
$_SESSION['MSG_FLAG'] = 0;
session_write_close();
header("location: admin.php");
exit();
}else {
die("Query failed: ".mysql_error());
}
}
else
{
// A common cause of file moving failures is because of bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writeable
$_SESSION['ERRMSG_ARR'] = array('Could not upload file. Check read/write persmissions on the directory');
header("Location: admin.php");
exit;
}
?>
I think
$pimage = $_FILES['image']['name'];
should be
$pimage = $_FILES['image'];
You probably missed this because your code is quite inconsistent - sometimes you use $pimage, while elsewhere you reference the $_FILES array directly. This makes it harder to maintain should the file field's name change. You could also type hint the valid() function to make PHP complain if $file isn't an array:
function valid(array $file) { ... }
What level of error reporting do you have set? It would highlight errors like trying to access undefined array keys.
See you are passing the image type in the line if (!valid($pimage))
But in the valid() function you are again trying to get the type of image $file['type'].
What George said should also work, but since you are making variables for the image type $ptype and name $pimage, you can use them itself.
So the changes should be $file['type'] becomes $file and $file['type'] & in the insert query $pimage['name'] becomes $pimage
I'm sure this solves it, Bahua ;)
<?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.
on a page, i have :
if (!empty($_FILES['logo']['name'])) {
$dossier = 'upload/';
$fichier = basename($_FILES['logo']['name']);
$taille_maxi = 100000;
$taille = filesize($_FILES['logo']['tmp_name']);
$extensions = array('.png', '.jpg', '.jpeg');
$extension = strrchr($_FILES['logo']['name'], '.');
if(!in_array($extension, $extensions)) {
$erreur = 'ERROR you must upload the right type';
}
if($taille>$taille_maxi) {
$erreur = 'too heavy';
}
if(!empty($erreur)) {
// ...
}
}
The problem is, if the users wants to edit information WITHOUT uploading a LOGO, it raises an error : 'error you must upload the right type'
So, if a user didn't put anything in the inputbox in order to upload it, i don't want to enter in these conditions test.
i tested :
if (!empty($_FILES['logo']['name']) and if (isset($_FILES['logo']['name'])
but both doesn't seems to work.
Any ideas?
edit : maybe i wasn't so clear, i don't want to test if he uploaded a logo, i want to test IF he selected a file to upload, because right now, if he doesn't select a file to upload, php raises an error telling he must upload with the right format.
thanks.
You can check this with:
if (empty($_FILES['logo']['name'])) {
// No file was selected for upload, your (re)action goes here
}
Or you can use a javascript construction that only enables the upload/submit button whenever the upload field has a value other then an empty string ("") to avoid submission of the form with no upload at all.
There is a section in php documentation about file handling. You will find that you can check various errors and one of them is
UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
<...>
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.
In your case you need code like
if ($_FILES['logo']['error'] == UPLOAD_ERR_OK) { ... }
or
if ($_FILES['logo']['error'] != UPLOAD_ERR_NO_FILE) { ... }
You should consider checking (and probably providing appropriate response for a user) for other various errors as well.
You should use is_uploaded_file($_FILES['logo']['tmp_name']) to make sure that the file was indeed uploaded through a POST.
I would test if (file_exists($_FILES['logo']['tmp_name'])) and see if it works.
Or, more approperately (thanks Baloo): if (is_uploaded_file($_FILES['logo']['tmp_name']))
We Could Use
For Single file:
if ($_FILES['logo']['name'] == "") {
// No file was selected for upload, your (re)action goes here
}
For Multiple files:
if ($_FILES['logo']['tmp_name'][0] == "") {
// No files were selected for upload, your (re)action goes here
}
if($_FILES["uploadfile"]["name"]=="") {}
this can be used
No file was selected for upload, your (re)action goes here in if body
echo "no file selected";
if ($_FILES['logo']['error'] === 0)
is the only right way