So, I'm trying to upload an image using move_uploaded_file(). Here is the code:
HTML FORM:
<form method="post" action="?page=prod&action=register" enctype="multipart/form-data">
<fieldset class="field-prods">
<label>Name:</label> <br>
<input type="text" name="txtName">
</fieldset>
<fieldset class="field-prods">
<label>Price:</label> <br>
<input type="number" name="nmbPrice">
</fieldset>
<fieldset class="field-prods">
<label>Image:</label> <br>
<input type="file" name="fileImage">
</fieldset>
<button type="submit" class="btn-prods">Register</button>
</form>
PHP SCRIPT:
if ($_POST != null) {
if (!empty($_POST['txtName']) && !empty($_FILES['fileImage']) && !empty($_POST['nmbPrice'])) {
Product::insert($_POST['txtName'], $_FILES['fileImage'], $_POST['nmbPrice']);
$target = "img/prods/" . $_FILES['fileImage']['name'];
$fileTmpName = $_FILES['fileImage']['tmp_name'];
move_uploaded_file($fileTmpName, $target);
}
}
But I'm getting lot of warnings:
*Warning: Array to string conversion*
*Warning: move_uploaded_file(img/prods/livraria-print1.jpg): Failed to open stream: No such file or directory*
*Warning: move_uploaded_file(): Unable to move "F:\Programs\Xampp\tmp\php7CE5.tmp" to "img/prods/livraria-print1.jpg"*
Can someone please help me with that?
# Array to string conversion
This warning is in insert function: you passed array ($_FILES['fileImage']) instead of string.
It seems that you want to store address of image, if that so it is better to store the image first then try to save the address of image.
# move_uploaded_file(img/prods/livraria-print1.jpg): Failed to open stream: ...
This warning is clear. check your directories and sure that the path you used is correct.
# move_uploaded_file(): Unable to move
And this one is because of prev warning.
Related
I am trying to upload .dat file, I want to get the content inside the file and have it in json.
I have this code:
HTML:
<from action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload">
<button type="submit" name"btnSubmit">Upload</button>
</form>
PHP:
If(isset($_POST["btnSubmit"])) {
$file = file_get_contents($_FILES["fileUpload"]["name"], true);
$r = json_encode($file);
}
The error I get is file_get_contents("fileName.dat"): failed to open stream
I am not trying to upload the file to my server or a folder, I am trying to get the data inside it and store it into json.
A file upload will save the file in the php's defined temporary directory. From there you can either move the file to a desired location, or get the content from it. In your case you can simply get the content by using "tmp_name" instead of "name".
Future more, you have to make sure you have the enctype set in your form.
<?php
// check if file is given
if(!empty($_FILES)) {
// get file from temporary upload dir
$file = file_get_contents($_FILES["fileUpload"]["tmp_name"], true);
$r = json_encode($file);
// show restult
var_dump($r);
}
?>
<!-- add multipart -->
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload">
<button type="submit" name"btnSubmit">Upload</button>
</form>
I have a webpage I'm building to allow users to upload multiple files to my webserver. Its a simple html page and php script. I'm having php errors and i'm not sure why. Any help is greatly appreciated.
Here is my html.
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
Your Name:
<select name="uname">
<option value="Test">Test</option>
</select>
<br>
Your Company:
<select name="company">
<option value="TestCom">testCompany</option>
</select>
<br>
Choose file(s) to upload (Max 500MB):
<input name="files[]" type="file" id="files" multiple="multiple" />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
and here is my php
<?php
$uname = $_POST['uname'];
$company = $_POST['company'];
$dir = "D:/File Upload/uploads/$uname/$company/";
$count = 0;
if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_FILES['files']))
{
// loop all files
foreach ( $_FILES['files']['name'] as $i => $name )
{
// if file not uploaded then skip it
if ( !is_uploaded_file($_FILES['files']['tmp_name'][$i]) )
continue;
// now we can move uploaded files
if( move_uploaded_file($_FILES["files"]["tmp_name"][$i], $dir . $name) )
$count++;
}
echo json_encode(array('count' => $count));
}
?>
Here is the errors in the php log.
[11-Feb-2015 16:01:04 America/Chicago] PHP Warning: move_uploaded_file(D:/File Upload/uploads/Test/TestCom/image.png): failed to open stream: No such file or directory in D:\File Upload\upload.php on line 17
[11-Feb-2015 16:01:04 America/Chicago] PHP Warning: move_uploaded_file(): Unable to move 'D:\phptempdata\php48F.tmp' to 'D:/File Upload/uploads/Test/TestCom/image.png' in D:\File Upload\upload.php on line 17
Turns out I didn't have the directories specified actually created on the files system.
I had been working so hard on just getting the file uploaded, I don't stop to ask if the folder was actually there.
I added this line to create the folder if it didn't exist.
if (!file_exists($dir)) { mkdir($dir, 0777, true); }
I am simply trying to save a file containing the serialized values of a form.
The Simple Form
<h2>PHP Form Validation Example</h2>
<form form method="post">
First Name: <input type="text" name="fname" value="
<?PHP
echo ($_POST['fname'])
?>">
<br><br>
<input type="submit" name="Save" value="Save Current Form">
Save File Name As: <input type="text" name="saveFile">
<br><br>
<input type="submit" name="Load" value="Load Old Form">
Load File: <input type="text" name="loadFile">
</form>
When i save/load the file i use the PHP code:
<?php
if (isset($_POST['Save'])) {
$PostArray = $_POST;
$s = base64_encode(serialize($PostArray));
$file = sprintf('/SavedForms/%s',$_POST['saveFile']);
file_put_contents($file, $s);
}
if (isset($_POST['Load'])) {
$file = sprintf("/SavedForms/%s",$_POST['loadFile']);
$_POST = unserialize(base64_decode(file_get_contents($file)));
}
?>
But it simply tells me
(when i try the save the file name "aaa")
that: "Warning: file_put_contents(/SavedForms/aaa) [function.file-put-contents]: failed to open stream: No such file or directory in"
I already have created the directory /SavedForms/ in the file as seen in the image below...
Could someone please let me know what i am doing wrong here!?!?
Remove the leading forward slash from the directory:
$file = sprintf('SavedForms/%s',$_POST['saveFile']);
Assuming that SavedForms is in the same directory as the executing php script.
Paths are relative to the script. By putting a leading slash, you are declaring an absolute path from the very root directory of your machine. This means it is currently looking for SavedForms in the root directory, and of course, it fails to find it
Trying to make a place for people to upload files to this site. I get an error when i try it. Let me know what you think. Im using codeigniter by the way
===== HTML =====
<div id="upload">
<form enctype="multipart/form-data" action="<?=current_url()?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload: <input name="uploadedfile" type="file" />
<br />
<input type="submit" value="Upload" />
</form>
<p><?=$uploadResult?></p>
</div>
===== PHP =====
if ($this->input->post()) {
$target_path = "../../uploads/";
$target_path = $target_path .basename($_FILES['uploadedfile']['name']);
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
$uploadResult = "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else {
$uploadResult = "There was an error uploading the file, please try again!"; /* <---- Error I get */
}
} else {
$uploadResult = 'didnt work at all';
}
echo $uploadResult;
$this->data['uploadResult'] = $uploadResult;
===== ERROR =====
A PHP Error was encountered
Severity: Warning
Message: move_uploaded_file(../../uploads/notes_USH.odt): failed to open stream: No such file or directory
Filename: controllers/discovery.php
Line Number: 158
Ensure that the directory "../../uploads/" exists and you have write permission. PHP wont will create this for you.
Also, CodeIgnter have a class to handle the file upload (may be useful). You can see this in the docs.
Ok so this is a little late but i just remade the whole thing with codeigniters stuff and after some tinkering with it i got it to work.
I have a form like
<form action="send.php" method="post" enctype="multipart/form-data">
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" />
</div>
<div>
<label for="image">Image</label>
<input type="file" name="image" />
</div>
<input type="submit" value="Send" />
</form>
PHP like
echo '<pre>'; print_r($_FILES); echo '</pre>';
if (move_uploaded_file($_FILES['image']['tmp_name'], 'images/' . $_FILES['image']['name'])) {
echo 'ok';
} else {
echo 'error!';
};
I keep getting error the print_r looks like
Array
(
[image] => Array
(
[name] => Untitled-1.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpprWdjN
[error] => 0
[size] => 61768
)
)
Activate error reporting, then you should see the error thrown by move_uploaded_file telling you what's wrong.
Your $_FILES looks file, error=0 means the upload completed successfully. Most likely it's a permissions error. You can try doing something like:
if (!is_writeable('images/' . $_FILES['image']['name'])) {
die("Cannot write to destination file");
}
However, be aware that you're using a user-provided filename, so if someone uploads "pwn_my_server.php", your script will write it out to the images directory, and then they can simply visit yoursite.com/images/pwn_my_server.php and take control of your site.
In general it is NEVER a good idea to trust anything in the $_FILES array, or use it directly, since the entirety of its contents are under remote user control. The only thing created by the server is the error code and tmp_name. The rest is potentially malicious.
maybe the problem is 'image/' folder, you can set the absolute path here and make sure that path is writable, then have a try.
Use the code below:
1. create the directory named 'uploads'
2. save the file with .php extension
now run the code.
<?php
if (!empty($_FILES))
{
// PATH TO THE DIRECTORY WHERE FILES UPLOADS
$file_src = 'uploads/'.$_FILES['image']['name'];
// FUNCTION TO UPLOAD THE FILE
if(move_uploaded_file($_FILES['image']['tmp_name'], $file_src)):
// SHOW THE SUCCESS MESSAGE AFTER THE MOVE - NO VISIBLE CHANGE
echo 'Your file have been uploaded sucessfuly';
else:
// SHOW ERROR MESSAGE
echo 'Error';
endif;
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div>
<label for="subject">Subject</label>
<input type="text" name="subject" />
</div>
<div>
<label for="image">Image</label>
<input type="file" name="image" />
</div>
<input type="submit" value="Send" name='submit' />
</form>
:)