Upload is reading PHP variable as null - php

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.

Related

Warning: Invalid argument supplied for foreach() - uploading photos form

Hi I'm new to php and keep getting this error: "Warning: Invalid argument supplied for foreach() in /home/site/folder/upload.php on line 61."
I'm trying to build a form in which users can upload one or more photos automatically to a directory to then be displayed else where.
Whenever I use this form I created it functions properly on my website but unfortunately it keeps printing that error out and would like it to go away. Here is my code I'm working with:
<div>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="images[]" multiple="multiple"/>
<input type="submit" name="submit" value="upload images"/>
<form/>
<?php
// check if uploads directory exists
$dir = "images/";
if(!is_dir($dir))
{
echo "Directory not found, let's create the folder.";
mkdir($dir,"0777", true);
}
$countimg = 0;
$allimg = 0;
foreach($_FILES["images"]["name"] as $k=>$name)
{
$allimg++;
$imgname = $_FILES["images"]["name"][$k];
$sizeimg = $_FILES["images"]["size"][$k];
$tmpname = $_FILES["images"]["tmp_name"][$k];
//2.
$extension = strtolower(pathinfo($dir.$imgname, PATHINFO_EXTENSION));
if($extension=='png' || $extension=='jpg' ||$extension=='jpeg' ||$extension=='gif')
{
if($sizeimg < 2097152){
if(!file_exists($dir.$imgname)){
//1.
if(move_uploaded_file($tmpname,$dir.$imgname))
{
$countimg++;
}
}
}
}
}
echo "You are trying to upload $allimg images".'<br>';
echo "From $allimg image(s) - $countimg was/were uploaded with success".'<br>';
$z = $allimg - $countimg;
echo "$z image(s) were not uploaded: Not an image, over 2MB, or already uploaded.";
?>
</div>
Try
if (count($_FILES)) {
foreach($_FILES["images"]["name"] as $k=>$name) {
....
}
}
I tested your script, it works fine. The error message appears because you are not checking that a file got uploaded before starting the foreach. If I land on the page, the PHP code will still be triggered. To fix this, you may use the below:
<div>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="images[]" multiple="multiple"/>
<input type="submit" name="submit" value="upload images"/>
<form/>
<?php
if( $_POST['submit'] ) {
$dir = "images/";
if(!is_dir($dir))
{
echo "Directory not found, let's create the folder.";
mkdir($dir,"0777", true);
}
$countimg = 0;
$allimg = 0;
foreach($_FILES["images"]["name"] as $k=>$name)
{
$allimg++;
$imgname = $_FILES["images"]["name"][$k];
$sizeimg = $_FILES["images"]["size"][$k];
$tmpname = $_FILES["images"]["tmp_name"][$k];
//2.
$extension = strtolower(pathinfo($dir.$imgname, PATHINFO_EXTENSION));
if($extension=='png' || $extension=='jpg' ||$extension=='jpeg' ||$extension=='gif')
{
if($sizeimg < 2097152){
if(!file_exists($dir.$imgname)){
//1.
if(move_uploaded_file($tmpname,$dir.$imgname))
{
$countimg++;
}
}
}
}
}
echo "You are trying to upload $allimg images".'<br>';
echo "From $allimg image(s) - $countimg was/were uploaded with success".'<br>';
$z = $allimg - $countimg;
echo "$z image(s) were not uploaded: Not an image, over 2MB, or already uploaded.";
}
?>
</div>
if( $_POST['submit'] ) will ensure that the form is submitted prior to running the rest of the PHP code.

Validating empty $_FILES

I have a simple register form where the user can upload a profile picture, if the user doesn't it, it should take the default picture name called person-icon.png.
When I register an user and upload a picture it works but if i leave it blank don't do anything and that column is inserted into the DB empty
if(isset($_FILES['image'])){
$img = $_FILES['image']['name'];
}
else if(empty($_FILES['image']['name'])){
$img = 'person-icon.png';
}
I already have tried these options:
Option 1:
if (empty($_FILES['image'])){
$img = 'person-icon.png';
}
else{
$img = $_FILES['image']['name'];
}
Option 2:
if($_FILES["image"]["error"] == 4)
Option 3:
if($_FILES["image"]["name"] == "")
You could check for $_FILE['image']['name'] not equal "" this work;
See code:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="image">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
<?php
//var_dump($_FILES);
$default_pic =" pic.png";
if (isset($_FILES['image'])){
if($_FILES['image']['name'] != ""){
echo "has pic";
}
else{
$_FILES['image']['name'] = $default_pic;
echo "has no pic";
}
}
?>
In order to check if a file has been uploaded you have to look for the tmp_name, because that is what contains the actual copy of your file content on the server.
I would do something like this:
$file = $_FILES['file']['tmp_name'];
if (!file_exists($file)){
//no image
}
else{
//image
}
You can also check $_FILES as long you don't upload other files in that form:
if(empty($_FILES)){
//no image
}
else{
//image
}
For further information check the official manual of file uploads.
I hope this helped you :)

Does an update have to be different to an insert when uploading a file?

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.";
}

PHP and html uploader

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.

php form send empty data online but works fine on localhost

i got some forms in php so i can upload data into a mysql database, i already do the trials on a localhost server with xampp, but when i upload my files into my host ftp the forms doesnt work,so, i was thinking it has something to do with the fact that i put this file and the "connect.php" one too under password restriction, and that has something to do with the file permissions too but i already grant permission to the user of the database and permission to the file and i also had tried without the password protected thing, and nothing, always had the same result, so i start to experiment a little and i figured out that the image uploads fine into the database but nothing else did it, knowing that i try to "echo out" the other input results but non of it show something, and i came into the conclusion that my form is sending empty data, SOMEONE CAN TELLME IF IM RIGHT?, WHY THIS IS HAPPENING! PLEASE HELP ,heres my code...
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<div id="slider_upload">
<h1>Slider principal</h1>
<div class="forma">
<form action="sliderPrincipal.php" method="post" enctype="multipart/form-data">
<p><label for="encabezado">Encabezado</label>
<input type="text" id="encabezado" name="encabezado" /></p><br>
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
<p><label for="fileupload">File to upload</label>
<input type="file" id="fileupload" name="fileupload" /></p><br>
<p><label for="articulo">Articulo</label>
<textarea id="articulo" name="articulo" rows="26" style="width: 100%;" >Escribir aqui</textarea></p><br>
<button type="submit" name="submit" value"send">Upload File</button>
</form><br><br>
</div>
</div>
<div class="message">
<?php
$file_dir = "../uploaded";
if (isset($_POST['encabezado'])){
$encabezado = mysql_real_escape_string($_POST['encabezado']);
$articulo = mysql_real_escape_string($_POST['articulo']);
}
foreach($_FILES as $file_name => $file_array){
//echo "path: ".$file_array['tmp_name']."<br />\n";
//echo "name: ".$file_array['name']."<br/>\n";
//echo "type: ".$file_array['type']."<br/>\n";
//echo "size: ".$file_array['size']."<br/><br/>\n";
//echo "encabezado ".$encabezado;
if(is_uploaded_file($file_array['tmp_name'])){
move_uploaded_file($file_array['tmp_name'], "$file_dir/".$file_array['name']) or die ("Your image couldnt be uploaded <br>");
$newpath = addslashes("uploaded/".$file_array['name']);
include "connect.php";
$addfile = "INSERT INTO slider (encabezado, image, articulo) VALUES ('$encabezado','$newpath', '$articulo')";
$result = mysql_query($addfile);
if ( $result === FALSE ) {
echo "your post could not be uploaded but we already got your image in our files ";
} else{
echo '<p style="padding: 20px;"><h1>Your post was successfully uploaded <h2></p><br><br>';
}
mysql_close();
} else "No file found";
}
?>
</div>
</div>
</body>
</html>
$file_dir = "../uploaded";
if($_REQUEST['submit']) {
$encabezado = mysql_real_escape_string($_POST['encabezado']);
$articulo = mysql_real_escape_string($_POST['articulo']);
foreach($_FILES as $file_name => $file_array){
if(is_uploaded_file($file_array['tmp_name'])){
move_uploaded_file($file_array['tmp_name'], "$file_dir/".$file_array['name']) or die ("Your image couldnt be uploaded <br>");
$newpath = addslashes("uploaded/".$file_array['name']);
include "connect.php";
$addfile = "INSERT INTO slider (`encabezado`, `image`, `articulo`) VALUES ('$encabezado','$newpath', '$articulo')";
$result = mysql_query($addfile);
if ( $result === FALSE ) {
echo "your post could not be uploaded but we already got your image in our files ";
} else{
echo '<p style="padding: 20px;"><h1>Your post was successfully uploaded <h2></p><br><br>';
}
mysql_close();
} else "No file found";
}
}
Try above code.
Note: not tested.

Categories