The problem I have is that my move_uploaded_file doesn't work.
I have the following code:
<input type="file" name="image<?=$a; ?>" />
$a is a variable to define each of the inputs because I have 4 ( I have them in a while)
The form has enctype="multipart/form-data"
The directory exists.
The following code is the php code I used to get the images
for($a=1; $a<=4; $a++){
$diretor = "../images/imprensa/".$_FILES['image'.$a]['name'];
$image = basename($_FILES['image'.$a]['tmp_name']);
if(move_uploaded_file($image, $diretor)){
echo "yey";
}else{
echo "Oh";
}
}
Already tried to print the variables and I get both temp_name and basename but the code doesn't seem to work
Where is the error here?
EDIT
The move_uploaded_file is INSIDE for, sorry for not clearing it out
Don't use basename() on the tmp_name parameter. The first argument to move_uploaded_file must be a tmp_name parameter. On the other hand, you should use it on name, since that comes from the user, and they might try to add other directory names.
You should also call it inside the loop, otherwise you're only moving the last file.
for($a=1; $a<=4; $a++){
if ($_FILES['image'.$a]['error'] == 0) {
$diretor = "../images/imprensa/".basename($_FILES['image'.$a]['name']);
$image = $_FILES['image'.$a]['tmp_name']);
if(move_uploaded_file($image, $diretor)){
echo "yey";
}else{
echo "Oh";
}
}
}
Related
I want to ask you guys about my code in my php update form.
I use unlink($file_Path) to Remove my image file in my folder & my server and that work fine!
So I wonder when using "unlink($file_Path)" to removing an image, In my php page it show me an "Image File Icon " when there was no picture (The image file was removed) But it show me like that (Image file Icon) Because, I though It still has a some value (my value = "../filename.jpg")
so I put "value=" "/" (None Value to Reset a Value)
example :
<input type="hidden" name="newSubimage1" value=""/>
and that work fine when I use with "!empty($ro.."
example :
if (isset($row['subimage1']) && !empty($row['subimage1']))
{
echo "<img src='../images/images_products/".$row['subimage1']."'>";
} else {
echo "No Image Here"; }
`
to not show an "Image File Icon"
Is that a correct way ? that I used to Removing file / Not display an Image File Icon or you has any easy way or the best way that you want to suggest me.
thanks
$image_file_ext = array('jpg', 'png', 'bmp');
$file_ext = pathinfo($row['subimage1'],PATHINFO_EXTENSION);
if (isset($row['subimage1']) && !empty($row['subimage1']) && in_array($file_ext, $image_file_ext))
{
echo "<img src='../images/images_products/".$row['subimage1']."'>";
} else {
echo "No Image Here";
}
I'm using this code to process uploaded files:
mkdir("files/" . $id, 0700);
$path = "files/" . $id;
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
foreach($_FILES['attachments']['name'] as $f => $name)
{
if($_FILES['attachments']['error'][$f] == 4)
{
continue;
}
if($_FILES['attachments']['error'][$f] == 0)
{
if(move_uploaded_file($_FILES["attachments"]["tmp_name"][$f], $path.$name))
{
$count++;
}
}
}
}
$id is a random number taken from the database. Besides, I'm using this markup:
<input type="file" id="attachments" name="attachments[]" multiple="multiple" accept="*">
While the exact same code had worked brilliantly before, it now throws numbers of errors I can't really deduce:
1: mkdir(): File exists in ... on line ... (<-- now, it doesn't for granted!)
2: Undefined index: attachments in ... on line ... (well, it's defined also using form method post!)
3: Invalid argument supplied for foreach() in ... on line ... (which is quite clear as the above stated errors do prevent the foreach from doing its job correctly)
Yes, I made sure that I'm actually using POST. I also tried changing the file input's name from attachments to any other, however, scenario remains the same.
Adding enctype="multipart/form-data" has done it.
1] Check for the folder rights 0777. Weather you are able to create directory or not
2] After posting form. Make sure your form has enctype = multipart/form-data tag.
In you file please check with
echo "<pre>";
print_r($_FILES);
exit;
If you are getting any data or not? If getting data then move ahead.
First check if your $id really contain something, secondly your form should have attribute of enctype = multipart/form-data for using input type file.
<form action="test.php" method="post" enctype="multipart/form-data">
Now in your case you will get the array of files you before your perform any work, see print_r of attachments:
echo "<pre>";
print_r($_FILES);
exit;
I am trying to upload image to database and getting this PHP error message:
Warning: move_uploaded_file(/upload/efc5ad334bca9f31b19d85a6cc2ada57/-416649605.jpg): failed to open stream: No such file or directory in C:\xampp\htdocs\learnphp\gettingstarted.php on line 51
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpA9E6.tmp' to '/upload/efc5ad334bca9f31b19d85a6cc2ada57/-416649605.jpg' in C:\xampp\htdocs\learnphp\gettingstarted.php on line 51
Upload Fail.
Here is my php script:
<?php
require("include/functions.php");
check_session();
$logged_user = $_SESSION['username'];
if(isset($_FILES['avator']['name']) && $_FILES['avator']['tmp_name'] !=""){
//setting file properties
$fileName = $_FILES['avator']['name'];
$filetmpLoc = $_FILES['avator']['tmp_name'];
$fileType = $_FILES['avator']['type'];
$filesize = $_FILES['avator']['size'];
$fileErrMsg = $_FILES['avator']['error'];
//explose the filename extention into an array
$kaboom = explode('.',$fileName);
$fileExt = end($kaboom);
list($width ,$height) = getimagesize($filetmpLoc);
if( $width <10 || $height <10 ){
//the image has not dimenssion
echo 'The Image has no dimension.Try again!';
exit();
}else{
// The image is has dimension so its OK
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
//check the size of the image
if($filesize > 1048576){
echo 'Your avator file size was larger than 1mb.';
exit();
}else if(!preg_match('/\.(gif|png|jpg)$/i',$fileName)){
echo"Your avator file was not JPG,PNG or GIF type.Try again.";
exit();
}else if($fileErrMsg == 1){
echo "Unknoan Error occured. Upload Fail.";
exit();
}
//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name");
if( $moveResult !=true){
echo 'Upload Fail.';
exit();
}else{
//resize the image
include_once("include/resizeimage.php");
$target_file = "user/$logged_user/$db_file_name";
$resize_file ="user/$logged_user/$db_file_name";
$wmax = 200;
$hmax = 230;
img_resize($target_file,$resize_file,$wmax,$hmax,$fileExt);
$sql = "UPDATE mygust SET avatar = '$db_file_name' WHERE username='$logged_user' LIMIT 1";
$query = mysqli_query($con,$sql);
mysqli_close($con);
exit();
}
}
}
?>
My HTML code is:
<form id="u_pro_pic" method="post" enctype="multipart/form-data" onSubmit="" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
<h2>Set your Profile Avator</h2><br>
<div id="av_wrap"><div id="avator_div"><img src="image/blank-profile.png" class="avator" title="Chose a file to upload" onClick="triggerUpload(event,'avator')"></div>
<div id="ad_clarleft">
<input type="button" class="add" title="Choose a file to upload" onClick="triggerUpload(event,'avator')" value="Add Avator"><br>
<hr>
<p>These brethren have uploaded their's and you should too. </p>
</div>
</div>
<input name="avator" type="file" id="avator" form="u_pro_pic" onChange="readURL(this)">
<input type="submit" name="u_avator" id="sumit" class="avt" value="Upload">
</form>
Please any help would be much appreciating.
PHP tries to move your uploaded file to a folder that does not exist:
//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name");
The path "/upload" does not look like a correct windows path. Change it to something like "C:\xampp\htdocs\learnphp\upload". Create this folder manually if it does not exist.
//move uploaded avator
$moveResult = move_uploaded_file( $filetmpLoc,"C:/xampp/htdocs/learnphp/upload/$logged_user/$db_file_name");
The reason why you're getting an error on the upload, is that the folder itself does not exist; least that's the impression I am getting from it and to be honest, we don't know if efc5ad334bca9f31b19d85a6cc2ada57 exists or not.
Sidenote: Use file_exists() which is referenced further down in this answer.
Since you are using sessions for $logged_user as the username session array, make sure the session was started inside all files using sessions. session_start(); must reside inside all files, and at the top of your code.
It is good practice to check if the session is also set using isset() or !empty().
References:
http://php.net/manual/en/function.session-start.php
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.empty.php
If not (which am pretty sure it doesn't), you would first need to create it using the mkdir() function.
http://php.net/manual/en/function.mkdir.php
The syntax is: mkdir("/path/to/my/dir", 0700); - 0700 can be changed to 0755 which is the usual setting for folders and it must be set so that the folder can be written to, using chmod.
http://php.net/manual/en/function.chmod.php
The syntax being, one of the 3 listed from the manual:
chmod("/somedir/somefile", 755); // decimal; probably incorrect
chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect
chmod("/somedir/somefile", 0755); // octal; correct value of mode
So, you will need to use the mkdir() function after the session file and before "moving" it to the folder created by $logged_user and its associated name.
I.e.:
mkdir("/path/to/your/dir", 0700); // you can use variables here
$moveResult = move_uploaded_file(...);
This part of your code /upload/ suggests using a full server path syntax.
move_uploaded_file( $filetmpLoc,"/upload/$logged_user/$db_file_name")
Either you use what your full server path is, for example:
/var/usr/public/upload/
or as referenced in another answer given C:/xampp/htdocs/learnphp/upload/
or a relative path:
I.e.:
upload/ or ../upload/ depending on the execution location of your script. The former being if executed from the root of the public area.
Nota: I am unsure if -416649605.jpg is the actual filename being uploaded, or if there is anything missing before the hyphen, or the hyphen is being added somewhere. You will need to look into that.
Pulled from my comment:
Now, if you're going to use a BLOB, that may not be big enough and may have to use a LONGBLOB https://dev.mysql.com/doc/refman/5.0/en/blob.html.
However, when using a BLOB to insert into the db directly, you will have to use mysqli_real_escape_string() for that, otherwise it won't work; you will get a syntax error thrown back.
Reference:
http://php.net/manual/en/mysqli.real-escape-string.php
So, keep on using error reporting until you can figure out where the problems may be occuring.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// if using MySQL
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Also add or die(mysqli_error($con)) to $query = mysqli_query($con,$sql); to check for database errors.
Reference:
http://php.net/manual/en/mysqli.error.php
Additional reference:
http://php.net/manual/en/function.file-exists.php (check if a file/folder exists)
Footnotes:
Your code in its present state is open to an SQL injection. Use a prepared statement
References:
https://en.wikipedia.org/wiki/Prepared_statement
How can I prevent SQL injection in PHP?
I believe I have given you enough information in order to point you in the right direction that will and hope will lead you to success, cheers!
Replace your $moveResult statement with the following two statement as you have to store the file in folder with a specific name.
$destination = "./".$_FILES['avator']['name'];
$moveResult = move_uploaded_file( $_FILES['avator']['tmp_name'],$destination);
The code below fetches a jpg image from a server. if the length is larger than 1, we assume to have successfully grabbed the file. Then it proceeds to create a folder for the user if it isnt already there. (this part works)
from there, it should save the file in the /media/downloads/username location
instead it is going to /media/downloads/
I've looked at my concatenation a few times now, but I don't see where the issue is. I SEE that the filename is coming out with the username attached to the front, so I imagine its just a concatenation error.
Once this is fixed, I have a bigger issue- because I am using rand, when I cycle the script it just gives me duplicates. how can I prevent the duplicate images?!
if (strlen($data) > 1) {
$prePath = 'media/download/from_'.$sender.'_to_'.$recipient.'_id_'.$snapid.'.jpg';
if (!file_exists('media/download/'.$username)) {
mkdir('media/download/'.$username, 0777, true);
}
if (file_exists($prePath)){
$finalPath = 'media/download/'.$username.'/from_'.$sender.'_to_'.$recipient.'_id_'.$snapid.rand(0,100).'.jpg';
}
else {
$finalPath = 'media/download/'.$username.'/from_'.$sender.'_to_'.$recipient.'_id_'.$snapid.rand(0,100).'.jpg';
}
//echo "<img src='$data'></img>";
file_put_contents($finalPath, $data);
echo " <img src='".$finalPath."' alt='Smiley face' height='100' width='100'> ";
}
I have a form with several
input type="file"
tags. How can I know on the server side amount of files uploaded by the user. He can upload 3 files, or may be 5 files, 1 or even nothing. I need to know how much files user have uploaded.
You can use the count or sizeof on $_FILES array that contains uploaded file info:
echo count($_FILES);
Update (Based on comments):
You can do this:
$counter = 0;
foreach($_FILES as $value){
if (strlen($value['name'])){
$counter++;
}
}
echo $counter; // get files count
If you are having input upload tags with name like file1, file2 then
if($_FILES['file1']['size'] > 0)
echo "User uploaded some file for the input named file1"
Now for many files (looking at the output you are having), run a foreach loop like this:-
$cnt=0;
foreach($_FILES as $eachFile)
{
if($eachFile['size'] > 0)
$cnt++;
}
echo $cnt." files uploaded";
I am not sure why the similar answer in How can I know a number of uploaded files with PHP? got downvoted? For the '0' ?
$_FILES is a global array of files which stores uploaded files.
Form:
<form enctype="multipart/form-data" ...>
<input type="file" name="image[]" multiple>
Script:
$c = sizeof($_FILES['image']['name']);