I initialize the variables, use move_uploaded_file function and then I write a basic form user will use to upload their photo. I am trying to print at lease an error_msg or a sucess_msg showing wether they had sucess in loading the file or not. nothings is showwing up. Help!
$error_msg = "";
$success_msg = "";
$name2 = "";
if ($_POST['parse_var'] == "pic"){
if (!$_FILES['fileField']['tmp_name']) {
$error_msg = '<font color="#FF0000">ERROR: Please browse for an image before you press submit.</font>';
} else {
$maxfilesize = 51200; // 51200 bytes equals 50kb
if($_FILES['fileField']['size'] > $maxfilesize ) {
$error_msg = '<font color="#FF0000">ERROR: Your image was too large, please try again.</font>';
unlink($_FILES['fileField']['tmp_name']);
} else if (!preg_match("/\.(gif|jpg|png)$/i", $_FILES['fileField']['name'] ) ) {
$error_msg = '<font color="#FF0000">ERROR: Your image was not one of the accepted formats, please try again.</font>';
unlink($_FILES['fileField']['tmp_name']);
} else {
$newname = $id'.jpg';
$place_file = move_uploaded_file( $_FILES['fileField']['tmp_name'], "images/$id/".$newname);
$success_msg = '<font color="#009900">Your image has been updated, it may take a few minutes for the changes to show... please be patient.</font>';
}
} // close else that checks file exists
}
<table width="709" align="center" cellpadding="5">
<form action="edit_profile.php" enctype="multipart/form-data" method="post" name="pic1_form" id="pic1_form">
<!-- <tr>
<td width="125" class="style7"><div align="center"><strong>Please Do First →</strong></div></td>
</tr>-->
<tr>
<td width="16%"><?php print "$user_pic"; ?></td>
<td width="74%">
<input name="fileField" type="file" class="formFields" id="fileField" size="42" />
50 kb max
</td>
<td width="10%">
<input name="parse_var" type="hidden" value="pic" />
<input type="submit" name="button" id="button" value="Submit" />
</td>
</tr>
</form></table>
You're going about checking if an upload was performed the wrong way:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... we're in a post situation, so check if a file was uploaded ...
if ($_FILES['fileField']['error'] !== UPLOAD_ERR_OK) {
$error_msg = "File upload failed with error code " . $_FILES['fileField']['error'];
} else {
... a file was successfully uploaded ...
... process it ...
if (!move_uploaded_file( ... )) {
$error_msg = "Failed to move file";
}
}
}
Checking for the presence of a form field is a poor way to check if a POST was performed. you may forget to put that field into the form, the name could change, etc... Checking the REQUEST_METHOD is guaranteed to work, as that is set regardless of what kind of request is being performed, and will always be the type of the request (get, post, head, etc...).
As well, don't use the user-provided file name to verify that they uploaded an image. That name can be trivially forged by simply renaming some OTHER kind of file to "whatever.jpg". Use server-side means to check if it's an image, such as FileInfo or getimagesize()
I think the error you're looking for is this one:
$newname = $id'.jpg';
You forgot a dot, and the whole script just crash:
$newname = $id.'.jpg';
I don't see anywhere in that code where you are echoing the error or success message.
Related
I am having trouble getting a picture to load from mysql database. The directory is randomly generated and gets stored in the database just fine. When the page refreshes the img returns a broken link, echos 'not set.', and inspect element tells me that $default_pic isn't defined. I can't figure out what is going on here can anyone help?
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$listingid = $_SESSION['edit_listing'];
if(isset($_FILES['listingpic'])){
if($_FILES['listingpic']['type']=="image/jpeg"||$_FILES['listingpic']['type']=="image/png"||$_FILES['listingpic']['type']=="image/gif"){
if($_FILES['listingpic']['size']<1048576){
$chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$rand_dir_name = substr (str_shuffle($chars), 0, 15);
mkdir("userdata/listingpics/$rand_dir_name/") or die("directory error");
if(file_exists("userdata/listingpics/$rand_dir_name/".$_FILES['listingpic']['name'])){
echo "File already exists.";
}
else{
move_uploaded_file($_FILES['listingpic']['tmp_name'], "userdata/listingpics/$rand_dir_name/".$_FILES['listingpic']['name']) or die("Failed to move file.");
$listing_pic_name = $_FILES['listingpic']['name'];
$listing_pic_query = mysql_query("UPDATE properties SET default_pic='$rand_dir_name/$listing_pic_name' WHERE id='$listingid'");
$check_def = mysql_query("SELECT default_pic FROM properties WHERE id='$listing_id'"); //ADDED
$def_rows = mysql_fetch_assoc($check_def); //ADDED
$def_pic = $def_rows['default_pic']; //ADDED
$default_pic = "userdata/listingpics/".$def_pic;//<-PROBLEM
header("Location: ../list_property/upload.php?id=".$listingid);
}
} else echo "File must not exceed 1MB.";
} else echo "File must be a JPEG, PNG, or GIF image.";
} else echo "Not set.";
?>
<form action="" method="POST" enctype="multipart/form-data">
<img src="<?php echo $default_pic; ?>" width="50%" height="50%"/><br>
<br>
<input type="file" name="listingpic" />
<input type="submit" name="uploadpic" value="Upload Picture">
</form>
When the you refresh the page after image has uploaded, the script refreshes, which means your $default_pic gets reset, so it gets empty.
If you want not to get rid of that error, you should write a query that pulls from database a default image and fills in variable.
I have been trying for like 2 days now and its been frustrating! so hopefully i will learn something new today :)
Right, i have a php page where i can upload up to 3 images, the code is in a table (shrinked down to show only image inputs)
<tr>
<td align="right">1st Image</td>
<td><label>
<input type="file" name="fileField1" id="fileField1"/>
</label></td>
</tr>
<tr>
<td align="right">2nd Image</td>
<td><label>
<input type="file" name="fileField2" id="fileField2" />
</label></td>
</tr>
<tr>
<td align="right">3rd Image</td>
<td><label>
<input type="file" name="fileField3" id="fileField3" />
</label></td>
the feilds are then stored in a upload slot via php -
if (isset($_FILES['fileField1'])) {
$errors = array();
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILES['fileField1']['name'];
$global_file_name1 .= $file_name;
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILES['fileField1']['size'];
$file_tmp = $_FILES['fileField1']['tmp_name'];
if (in_array($file_ext, $allowed_ext) === false) {
$errors[] = 'Extention not alowed';
}
if ($file_size > 2097152) {
$errors[] = 'File must be under 2MB';
}
if (empty($errors)) {
move_uploaded_file($file_tmp, 'upload/'.$file_name);
} else {
foreach ($errors as $error) {
echo $error, '<br />';
}
}
Code is same for all 3
My problem is on the edit pages where you can change the other feilds (like name, details etc) when you then press submit the name is then changed to nothing as after a submit it submits what it has got which is nothing as the image hasnt been changed and was left.
My question is can i find a way of stopping the image if statement from going if nothing has been selected?
Thanks in advance!
You can check the file size:
if ($_FILES['fileField1']['size']>0) {
// new file has been submitted. Process it.
} else {
// an empty field has been submitted. Do nothing.
}
I am trying to Upload an image and store it in the database. I have mentioned the code, but it is not working for me. I'm not able to find the bug. Please see if anybody can find the bug.
The code is:
<?php
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
if($_REQUEST['submit'])
{
if(($_FILES['file']['type']=="image/jpeg" or $_FILES['file']['type']=="image/pjpeg" or $_FILES['file']['type']=="image/gif") and ($_FILES['file']['size']<300000))
{
if($_FILES['file']['error']>0)
{
$err=" ERROR :: ".$_FILES['file']['error'];
}
else
{
echo "Upload :".$_FILES['file']['name']."<br/>";
echo "Type: ".$_FILES['file']['type']."<br/>";
echo "Size: ".($_FILES['file']['size']/1024)."Kb<br/>";
echo "Stored in: ".$_FILES['file']['tmp_name']."<br/>";
move_uploaded_file($_FILES['file']['tmp_name'],"upload/".$_FILES['file']['name']);
echo $_FILES['file']['name'];
echo $_FILES['file']['tmp_name']."qwerty";
$n=3000;
$fo=fopen("upload/".$_FILES['file']['name'],"r");
$fr=fread($fo,$n);
mysql_query("update user set pic='$fr' where id='$id'");
}
}
else
{
$err=" ERROR :: Invalid Image";
}
mysql_query("update user set name='$name' where id='$id'");
mysql_query("update user set email='$email' where id='$id'");
}
$sql="select * from user where id='$id'";
$con=mysql_query($sql);
list($idR,$nameR,$emailR,$pwdR,$dateR,$picR)=mysql_fetch_array($con);
?>
<body>
<form action="" method="post" enctype="multipart/form-data">
<table>
<tr>
<td colspan="2"><?php echo $err; ?></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name" value="<?php echo $nameR ?>" /></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email" value="<?php echo $emailR ?>" /></td>
</tr>
<tr>
<td><label for="file">Upload or Change Pic:</label></td>
<td><input type="file" name="file" id="file" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Save"/></td>
</tr>
</table>
</form>
</body>
My code is not even able to upload the file. When I tried to echo the following, I found them empty:
echo "Name:".$_FILES['file']['name']."<br/>";
echo "Type: ".$_FILES['file']['type']."<br/>";
echo "Size: ".($_FILES['file']['size']/1024)."Kb<br/>";
echo "Stored in: ".$_FILES['file']['tmp_name'];
All the above fields are empty.
I don't know how this work but it didn't worked. I guess the problem is somewhere in my HTML code because the $_FILES values are none/empty. It is not retrieving the value from the form tag please check if my answer is incorrect to solve the problem or correct to how to solved this hard problem from science or other subject in computers and it form to been error or successfully.
Try this!
<?php
if(isset($_POST['submit']) && $_FILES['file']['size'] > 0)
{
// Data
$file_name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
// Check
$type = array(
'image/jpeg',
'image/gif',
'image/png',
);
$size = 300000;
if(in_array($file_type, $type) AND $file_size > $size)
{
echo 'Ooops! File type must be JPG, GIF or PNG. Or file size too big';
exit();
}
// Is error?
if ($_FILES["file"]["error"] > 0)
{
echo 'Upload Error';
exit();
}
else
{
echo 'File Name : '.$file_name.'<br />';
echo 'File Size : '.($file_size / 1024).' Kb<br />';
echo 'File Type : '.$file_type;
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Save"/>
</form>
If $_POST and $_FILES are both empty then you've exceeded the maximum post size ini ('post_max_size')
There are several settings in php.ini, including the maximum for an individual file ('upload_max_filesize'), and the maximum for all uploads ('post_max_size'). Make sure those ini settings are set correctly
Be careful of syntax if you hve edited it, it's picky when handling M, K or G (not KB, MB or GB), and don't exceed the bit size of your server, i.e. don't go above 4billion bytes on a 32 bit server.
Other causes of $_FILES being empty, but not $_POST. You don't have enough free space to upload your files, or you don't have permissions ot write to the temp directory. Check /tmp has enough space, and that you can write to it as apache/php user.
It worked when I moved my code on an independent .php file. And when I needed to upload I gave the link to that page in which independent uploading code was written. I don't know the reason behind this but this is how I solved it.
hmm....
try to change this line
if($_REQUEST['submit'])
to be
if(isset($_REQUEST['submit']))
and i think, this code
if(($_FILES['file']['type']=="image/jpeg" or $_FILES['file']['type']=="image/pjpeg" or $_FILES['file']['type']=="image/gif") and ($_FILES['file']['size']<300000))
can be simplified into
if(ereg("jpeg|pjpeg|jpg|gif|png", $_FILES['file']['type']) AND $_FILES['file']['size']<300000)
Good luck...
well I can upload image, mp3, mp4, .doc file etc with the following form. But it's doesn't upload .flv file. Anyone can tell me what is the problem in my code or how can i upload .flv..
<?php
$mysql_connect = mysql_connect("localhost", "root" );
mysql_select_db("vedio");
ini_set('upload_max_filesize','1000M');
if(isset($_POST['action']) == "upload")
{
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$size = $_FILES['file']['size'];
$type = $_FILES['file']['type'];
$name = str_replace(" ", "", $name);
$sql = mysql_query("INSERT INTO content VALUES('',
'$name', '$tmp_name', '$size' )");
if($sql)
{
echo "successfully uploaded";
}
else
{
echo "Something is wrong to upload";
}
$upload = "vedio/";
move_uploaded_file($_FILES['file']['tmp_name'], $upload . $name);
echo "<br/>";
echo $name;
echo "<br/>";
echo $tmp_name;
echo "<br/>";
echo $size;
echo "<br/>";
echo $type;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000000000" />
<table width="400" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="submit" value="upload" name="action" /></td>
</tr>
</table>
</form>
Many Thanks.
Shibbir
My guess is your flv is probably just too big..
upload_max_filesize alone is not enough to set, you also need to set post_max_size otherwise your POST request will be empty and your upload will fail (it'll essentially look like a non-post request).
This line doesn't make sense
if(isset($_POST['action']) == "upload")
you are calling isset() which is going to return true or false depending upon if that variable is given a value and then you compare that true or false with the string "upload" which obviously would never be equal. You either need to check if the variable is set or check if the value is equal to "upload".
if(isset($_POST['action']) && $_POST['action'] == "upload")
Should also check for file upload errors. Something like:
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else {
echo "No file upload errors";
}
I have created a form and everything is working fine so far. The only thing I have left is to reset the fields when the form is submitted. This seems like an easy task but after looking around and trying some things nothing seems to do the trick :( What I have now was taken from another post but my submit event was different from theirs which is why I think its not working. Any help is much appreciated.
php part
/////////////////////////////////upload image
//define a maxim size for the uploaded images in Kb
define ("MAX_SIZE","500");
//This function reads the extension of the file. It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
//This variable is used as a flag. The value is initialized with 0 (meaning no error found)
//and it will be changed to 1 if an errro occures.
//If the error occures the file will not be uploaded.
$errors=0;
//checks if the form has been submitted
if(isset($_POST['submit']))
{
//reads the name of the file the user submitted for uploading
$image=$_FILES['image']['name'];
//if it is not empty
if ($image)
{
//get the original name of the file from the clients machine
$filename = stripslashes($_FILES['image']['name']);
//get the extension of the file in a lower case format
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
{
//print error message
echo '<h1>Unknown extension!</h1>';
$errors=1;
}
else
{
//get the size of the image in bytes
//$_FILES['image']['tmp_name'] is the temporary filename of the file
//in which the uploaded file was stored on the server
$size=filesize($_FILES['image']['tmp_name']);
//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
echo '<h1>You have exceeded the size limit!</h1>';
$errors=1;
}
$newname="storeImages/".$filename;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
echo '<h1>Copy unsuccessfull!</h1>';
$errors=1;
}}}}
//If no errors registred, print the success message
if(isset($_POST['submit']) && !$errors)
{
echo "<h1>File Uploaded Successfully!</h1>";
}
//direct to same page but refresh
//header('Location: storeListForm.php');
?>
The form
<body>
<script type="text/javascript">
function onFormSubmit ()
{
document.storeList.reset();
return true; // allow form submission to continue
}
</script>
<div id="signUp">
<?php
//if the validation falls back to php, then print the validation error
if (isset($error_message)) echo $error_message;
?>
<form method="post" action="" id="storeList" name="storeList" enctype="multipart/form- data">
<table>
<tr>
<td><label for="name">Name</label></td>
<td><input type="text" name="name" id="name" value="<?php if (isset($_POST['name'])) echo $_POST['name'];?>"/></td>
</tr>
<tr>
<td> <label for="storeLocation">Location</label></td>
<td><input type="text" name="storeLocation" id="storeLocation" value="<?php if (isset($_POST['storeLocation'])) echo $_POST['storeLocation'];?>"/></td>
</tr>
<tr>
<td><label for="featured_items">Featured Items</label></td>
<td><input type="text" name="featured_items" id="featured_items" value="<?php if (isset($_POST['featured_items'])) echo $_POST['featured_items'];?>"/></td>
</tr>
<tr>
<td><label for="keywords">Keywords</label></td>
<td><input type="text" name="keywords" id="keywords" value="<?php if (isset($_POST['featured_items'])) echo $_POST['keywords'];?>"/></td>
</tr>
<tr>
<td><label for="fileImage">Image</lable></td>
<td><input type="file" name="image"></td>
</tr>
<td>Description</td>
<td> <textarea for="description"></textarea type="text area" name="description" id="description" value="><?php if (isset($_POST['description'])) echo $_POST['description'];?>"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" id="submit" value="Add Store" onsubmit="this.submit(); this.reset(); return false;"></td>
</tr>
</table>
</form>
</div>
</body>
Perhaps you're looking for this?
onClick="this.form.reset()"
(Yours is only this.reset()).