I want upload images in php here is my code
if (isset($_FILES['userfile']['name'])) {
if ($_FILES['userfile']['error'] == UPLOAD_ERR_OK) {
$from = $_FILES['userfile']['tmp_name'];
$to = "/var/www/html/images/".$_FILES['userfile']['name'];
$res = move_uploaded_file($from, $to);
if($res)
{
print 'upload success';
}
else
{
print 'fail';
}
here i got output fail please tell me correct process
thanks in advance
for images/ have you checked the Permission on Linux it will be 755 or 777.
Note: You don't need absolute path for that you can even do like below.
$to = "images/".$_FILES['userfile']['name'];
The code looks OK, so either the script cannot write to unsifficient rights on the /var/www/html/images/ directory, or that directory does not exist at all.
Please check the existance of the directory, and then try to write another file (not through upload) to that directory. Check the directory permissions accordingly.
Please try this, it is already tested and working fine.
<?php
mysql_connect("localhost","root","");
mysql_select_db("kerala");
error_reporting(0);
?>
<?php
if($_POST[sub1]=="Upload")
{
#mkdir("image");
$link="image/".time()."-".$_FILES[fil][name];
copy($_FILES[fil][tmp_name],$link);
$sql2="insert into `details`(`photo`) values('$link')";
$query2=mysql_query($sql2);
header("location:photo.php");
}
$sql3="select * from `details`";
$query3=mysql_query($sql3);
while ($row=mysql_fetch_array($query3))
{
//echo "<a href=`$row[photo]`><img src='$row[photo]' height='100' width='100'>$row[photo]</a>";
echo "<img src='$row[photo]' height='100' width='100'>";
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fil">
<input type="submit" name="sub1" value="Upload">
</form>
Related
i'm currently working on a small script for my Homepage but i ran into a problem.
I Try to upload an Image, but it seems like the POST data from the form is not being received. What did i do wrong?
I already changed the post_max_size and everything in the php.ini.
These are the Errors i get:
"Notice: Undefined index: image in ...." & "Notice: Undefined index:
submit in ...."
<form method="POST" action="/eye/sites/handling/post.php" enctype="multipart/form-data">
<div class="fileUpload">
<span><i class="fa fa-folder-o" aria-hidden="true"></i> Bild wählen</span>
<input type="file" class="upload" name="image"/>
</div>
<input type="submit" value="Upload It!" name="submit"/>
</form>
<?php session_start();
error_reporting(E_ALL);
if (isset($_SESSION["login_stat"])) {
date_default_timezone_set('Europe/Berlin');
$config = "$_SERVER[DOCUMENT_ROOT]/eye/more/config.xml";
$xml = simplexml_load_file($config);
$picWidth = $xml->pic->width;
$picHeight = $xml->pic->height;
$fulldate = date('dmYHis');
if(isset($_POST["submit"])) {
if (file_exists($_FILES['image']['tmp_name']) || is_uploaded_file($_FILES['image']['tmp_name'])) {
$typeCheck = $_FILES['image']['type'];
if ($typeCheck != "image/jpeg") {
$error = "Not a .jpg";
header('location: /eye/sites/post.php?stat=bad&error='.$error);
exit;
}
$file = $_SERVER['DOCUMENT_ROOT']."/uploads/".$fulldate.".jpg";
$type = "image/jpeg";
move_uploaded_file($_FILES['image']['tmp_name'], $file);
$file_thmb = $_SERVER['DOCUMENT_ROOT']."/uploads/!1A_thmb/".$fulldate.".jpg";
include "resize-class.php";
$resizeObj = new resize($file);
$resizeObj->resizeImage($picWidth, $picHeight, 'crop');
$resizeObj->saveImage($file_thmb, 100);
// header('location: /eye/sites/post.php?stat=good');
} else{
// header('location: /eye/sites/post.php?stat=bad&error=No File');
}
} else{
// header('location: /eye/sites/post.php?stat=bad&error=No Data');
echo $_SERVER['CONTENT_TYPE'];
echo "<br>";
echo $_FILES['image']['tmp_name'];
echo "<br>";
echo $_POST['submit'];
echo "<br>";
}
} else {
header('location: /eye/index.php?stat=in');
}
?>
Edit:
The problem is definitely about my Localhost.
This whole thing is working fine on my Webspace, but on my localhost it's not working.
BUT: I'm not getting errors anymore, when is click on Submit it goes to the php file that should save the image, but nothing is happening. I just see a white Page.
But like i said, it runs perfectly on my webspace..
If this is running on your local machine, do a quick check to make sure your "php.ini" file is configured to allow file uploads.
php.ini
file_uploads = On
The codes look fine. Check if your form action is posting to the correct path and if I may suggest using a simpler approach to test your file upload function before making it more complex. Use the following to start testing.
if (isset($_POST["submit"])) {
if (file_exists($_FILES['image']['tmp_name']) || is_uploaded_file($_FILES['image']['tmp_name'])) {
echo "Upload is working!";
}
}
Keep us updated on your findings.
Perhaps this general information will help someone, as it helped me: a submitted form will only include fields that have defined 'name' attributes. 'id' is not enough.
The idea is that 'id' identifies an element in the DOM for use by JavaScript (either as a global variable or for use in document.getElementById(ID)), but 'name' identifies those elements whose names and values will be sent to the destination ('action') page.
So it makes sense that there are two different identifying attributes, used in two different ways.
I'm looking to return to the previous page after a file upload and have "file uploaded successfully" on the upload page.
In upload.php at the top I have placed
sesssion_start();
And at the end of the file upload script I have placed
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
Now I know i need to put some code into the html document but unsure what needs to go in. Below is my html form script
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000" />
Select video to upload:
Please choose a file: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File" />
I know it is going to be something similar to this but unsure how or where I would place it.
session_start();
if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) {
echo "File uploaded successfully";
}
If someone could walk me through adding the HTML code into the correct place I will be very greatful
After the comments i amend my php code to look like this.
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
sesssion_start();
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name'] );
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'] , $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name'] ). " has been uploaded";
}
else {
echo "Sorry, there was a problem uploading your file.";
}
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
exit();
And the syntax inside the stream.php to:
<?phpsession_start();
if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) {
echo "File uploaded successfully";
}
?>
Thanks,
Mark
Nota: You also cannot use echo and header together because that would considered as outputting before header, so we'll just use a session array as the message and the header to redirect to "upload_form.php", then show the respective message on that page afterwards.
Use session_destroy() also to destroy any previous sessions.
Sidenote: Use two seperate files.
HTML form: call this "upload_form.php"
<?php
session_start();
session_destroy();
?>
<form action="stream.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="90000000" />
Select video to upload:
Please choose a file: <input name="uploadedfile" type="file" /><br />
<input type="submit" value="Upload File">
</form>
<?php
if(isset($_SESSION['upload_success'])){
echo $_SESSION['upload_success'];
}
else{
echo "Please select a file.";
}
?>
PHP (file 2): call this "stream.php"
<?php
session_start();
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name'] );
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'] , $target))
{
$_SESSION['upload_success'] = "File successfully uploaded.";
header("Location: upload_form.php");
exit;
}
else {
$_SESSION['upload_success'] = "Sorry, there was a problem uploading your file.";
header("Location: upload_form.php");
exit;
}
Edit:
Modify and add the following after if(move_uploaded_file...
if(isset($_FILES['uploadedfile']) && !empty($_FILES['uploadedfile'])){
$target_path = "upload/";
$target = $target_path . basename($_FILES['uploadedfile']['name']);
}
Your code works fine, but you should remove session['upload_success'] with unset function after you do echo success message.
try
unset( $_SESSION['upload_success'])
in stream.php right after
echo "File uploaded successfully";
update :
if you want to work all these on a single page, You can simply do it like below:
if(isset($_SESSION['upload_success']) and $_SESSION['upload_session'])
{
//echo success message
//remove session
}
if(isset($_POST['file'])){
//upload process , if it was successfull make seesion true...
}
else {
//show form
}
For a quick solution, you could use Ravi Kusuma's jQuery File Upload Plugin or an AJAX solution to do this.
Another alternative, though, to those proposed above is to programmatically construct / output an HTML form with some javascript, and get it to POST a message to stream.php:
CAVEAT: I haven't tried this myself, but I can't think why it wouldn't work. Would someone please confirm my sanity? -- Tested it myself: it works.
<?php
//upload.php
//Do file upload stuff, then:
$out = '
<form id="frmUpOkay" action="stream.php" method="post">
<input name="upMsg" value="Upload Successful" />
</form>
<script type="text/javascript">
$(function(){
$("#frmUpOkay").submit();
});
</script>
';
echo $out;
?>
You must also add this bit to the top of the stream.php file:
<?php
if ( isset($_POST['upMsg']) && isset($_POST['upMsg']) != '' ){
$upMsg = $_POST['upMsg']; //you should sanitize this input
}else{
$upMsg = '';
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div>
Your normal website content is here.<br>
<br>
Upload message: <?php echo $upMsg; ?> <br>
<br>
</div>
</body>
Notes:
Above code uses jQuery, so you would need the jQuery library included on your upload.php page (as shown above).
Placing
$_SESSION['upload_success'] = TRUE;
header("Location: stream.php");
At the end, I believe, would set true no matter what actually happened with the file's upload the reason being, there is not a condition being checked.
Unless the script has an exit command when it fails, it will eventually get to the part where it says: "Set the upload success as true and then go to stream.php" rather than saying, "If the upload is successful, set the upload success as true and then go to stream.php"
I would try:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
if($_FILES['uploadedfile']['size'] == 0)//In other words, if no file was selected.
{
$_SESSION['upload_success'] = 4;//File wasn't selected
header("Location: stream.php");
exit();
}
if(!file_exists('upload/' . basename($_FILES['uploadedfile']['name'])))
{
$_SESSION['upload_success'] = (move_uploaded_file($_FILES['uploadedfile']['tmp_name'],'upload/' . basename($_FILES['uploadedfile']['name'])) ? 1 : 2);
}
elseif(file_exists('upload/' . basename($_FILES['uploadedfile']['name'])))
{
$_SESSION['upload_success'] = 3;
}
header("Location: stream.php");
exit();
?>
Now in stream.php where you have your if statement that displays the message do this instead:
<?php
session_start();
switch (#$_SESSION['upload_success']) {
case 1:
echo "File uploaded successfully";
break;
case 2:
echo "Sorry, there was a problem uploading your file.";
break;
case 3:
echo "A file with that name already exists!";
break;
case 4:
echo "You must select a file to upload!";
break;
}
unset($_SESSION['upload_success']);
?>//So if you reload stream.php yet another time no messages will be displayed again for no reason. ie. none of the cases will match an unset variable.
Last, you cannot echo (or do any type of output meant to be viewed by a user) before you header(Location: "somepage.php");
The page will switch before the user can read the output.
The way your code is currently written in your question you could have the following happen:
The server echos "Sorry, there was a problem uploading your file", which will never be seen by the user.
$_SESSION['upload_success'] is then set to TRUE, which is obviously not in agreement with #1.
It then sends the user to stream.php where a success message is
displayed.
An alternate, lazier way with less useful scenario descriptions to also fix your problem would be to do this instead (in upload.php):
else
{
die("Sorry, there was a problem uploading your file.");
}
Hope that helps!
Back again with another newbie question. I've been working on a document that will allow users to upload their own avatars to a blog that I'm creating to learn some PHP. I've been working on this document for two days now and I've spent over six hours of searching and trying different things to fix it but I just can't get it to get past this:
if(move_uploaded_file($_FILES['avatar']['name'], $target)){
//good message
echo "Your avatar was successfully uploaded.";
}else{
//bad message
echo "Your avatar couldnt be uploaded, please contact an admin.";
}
It does send the "bad message" finally after about an hour of trying different solutions but I'm not quite sure why it is giving me the "bad message", to me everything looks okay.
FULL CODE:
<?php
session_start();
if (isset($_SESSION['username'])){
if (isset($_POST['submit']) && isset($_FILES['avatar'])) {
$con = mysql_connect("localhost","root","");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db('webserver', $con);
$username = $_SESSION['username'];
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$id = $row['id'];
//Directory to save stuff
$target = "images/useravatars";
$target = $target . basename($_FILES['avatar']['tmp_name']);
//Save the avatar
if(move_uploaded_file($_FILES['avatar']['name'], $target)){
//good message
echo "Your avatar was successfully uploaded.";
}else{
//bad message
echo "Your avatar couldnt be uploaded, please contact an admin.";
}
}else{
echo "38";
}
}
?>
<form enctype="multipart/form-data" action='uploadavatar.php' method='POST'>
<table>
<tr>
<td>
Upload an avatar:
</td>
</tr>
<td>
<input type='file' name='avatar'>
</td>
</tr>
</table>
<p>
<input enctype='multipart/form-data' type='submit' name='submit' value='Submit'>
</p>
</form>
By the way I'm sorry there is probably a bunch of useless code in there, I have spent a bunch of time just getting it far enough to give me an error.
The location where the uploaded file is stored on disk is $_FILES['avatar']['tmp_name']. You want to move that, not $_FILES['avatar']['name'].
The problem here is that, you're using move_uploaded_file() in wrong way.
The first parameter requires a filename with its extension, without base path, like
mypic.jpg. The second requires a destination where that file should be uploaded.
As for your code,
Replace this,
//Directory to save stuff
$target = "images/useravatars";
$target = $target . basename($_FILES['avatar']['tmp_name']);
//Save the avatar
if(move_uploaded_file($_FILES['avatar']['temp'], $target)){
with
// I'd assume that dirname(__FILE__) refers to your root
//Directory to save stuff
$destination = sprintf('%s/images/useravatars/%s', dirname(__FILE__), $_FILES['avatar']['name']);
//Save the avatar
if (move_uploaded_file($_FILES['avatar']['tmp_name'], $destination)) {
I have a form with a file field called image, but this field is not required.
When user don't choose any file in form, the do_upload() always return a error.
How can I check if user chosen a file before perform the upload action in my controller?
Please use empty()
if (empty($_FILES['userfile']['name'])) {
}
Try to check if the file is valid using is_uploaded_file(). For example:
if(is_uploaded_file($_FILES['userfile']['tmp_name']))
{
do_upload();
}
In your controller, on the function that receives the submitted form:
if (isset($_FILES['image']['name']) && !empty($_FILES['image']['name'])) {
// do_upload
}
Here is full script to check if file field is empty or not in php
<!DOCTYPE html>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
Select image to upload:
<input name="my_files[]" type="file" multiple="multiple" />
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if (isset($_FILES['my_files']))
{
$myFile = $_FILES['my_files'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i <$fileCount; $i++)
{
$error = $myFile["error"][$i];
if ($error == '4') // error 4 is for "no file selected"
{
echo "no file selected";
}
else
{
$name = $myFile["name"][$i];
echo $name;
echo "<br>";
$temporary_file = $myFile["tmp_name"][$i];
echo $temporary_file;
echo "<br>";
$type = $myFile["type"][$i];
echo $type;
echo "<br>";
$size = $myFile["size"][$i];
echo $size;
echo "<br>";
$target_path = "uploads/$name"; //first make a folder named "uploads" where you will upload files
if(move_uploaded_file($temporary_file,$target_path))
{
echo " uploaded";
echo "<br>";
echo "<br>";
}
else
{
echo "no upload ";
}
}
}
}
?>
</body>
</html>
But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations.
refer http://www.techzigzag.com/how-to-check-that-user-has-upload-any-file-or-not-in-php/
Hope it will help you.
Just use native php code to check file upload.
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
use empty() empty function does check if the file field is empty or not
if ( ! empty($_FILES)) {...}
if(!empty($_FILES['myFileField'])) {
// file field is not empty..
} else {
// no file uploaded..
}
As file upload error "No file selected" is number 4, correct way of doing this is:
if ($_FILES['my_image_field_name']['error'] !== 4){
if ($this->upload->do_upload('my_image_field_name')) { ...
When checking by name or tmp_name, there might be other reasons why these fields didn't get populated, and you may miss these.
if(!empty($_FILES[$file_name]['name'])){
// TODO your logic
}else{
echo "empty";
}
$file['file']->isValid()
CI4 user guide link
I have the following PHP code that I am using to upload an image to MySQL. When I click submit nothing happens.
include ("connect.php");
session_start();
$login = $_SESSION['wname'];
if((#$_POST['submit'])&&(isset($_FILES["myfile"]))){
// properties of the uploaded file
$name = $_FILES["myfile"]["name"];
$type = $_FILES["myfile"]["type"];
$size = $_FILES["myfile"]["size"];
$temp = $_FILES["myfile"]["tmp_name"];
$error = $_FILES["myfile"]["error"];
if($name){
die("Error uploading file! Code $error.");
} else {
$place = "avatars/$name";
move_uploaded_file($tmp_name,$place);
$query = mysql_query("UPDATE page SET pid_image_name = '$place' WHERE wname = '$login' ");
die("upload complete <a href='index.php'>View image</a>");
echo "Upload complete!";
}
} else {
die("select a file");
}
Here's my form:
<form action='up.php' method='POST' enctype='multipart/form'>
<input type='file' name='myfile'>
<p> <input type='submit' name='submit' value="upload">
What am I doing wrong?
Another important parameter to check out in php.ini is post_max_size. If you set upload_max_filesize > post_max_size the result is that no data is written to $_POST nor $_FILES for files which sizes exceed post_max_size but are below upload_max_filesize
Format you're code.
Are you submitting the actual HTML form (not the PHP code) as html/multipart?? I am willing to be you're not. (enctype="multipart/form-data" needs added to your form tag!)
Learn to debug - actually put conditions elsewhere and see where your code is failing!
In your HTML for have you got enctype="multipart/form-data"?
Something like this:
<form action='submit.php' method='post' enctype="multipart/form-data">
Edit 1:
if you do this: if(move_uploaded_file($tmp_name, $place)){
echo "did move file<br />";
}else{
echo "move failed<br />";
}
You will get move failed (Or I do with your code)
Edit 2
I found your problem: you misspelt the temp-dir variable: you defined $temp but in the move_uploaded_file you asked for $tmp_name so here the correct code: move_uploaded_file($temp, $place);
Just in case you can't see any errors activate error reporting by setting error_reporting(E_ALL); right after the php tag.