var_dump not returning a value - php

I want to allow a user the upload an image (file) for their profile picture, on my website. They upload the image via an HTML form, but I am having trouble moving the file to the folder I want it to. I don't want to mess with the php.ini file to change the upload path. I want to use move_uploaded_file(). I try and use $tmp= $_FILES['picture']['tmp_name'] and var_dump($tmp), but It keeps returning a value of (0). So, I think the problem has something to do with that. Here is my code,
Here is my HTML:
<form enctype="multipart/form-data" method="post" action="upload_img.php">
<input type="hidden" name="MAX_FILE_SIZE" value="32768"/>
<input type="text" name="name" value=""/>
<input type="file" name="picture" value="picture"/>
<input type="submit" name="submit" value="upload"/>
</form>
And my PHP:
<?php
define('GW_UPLOADPATH', 'images/');
$picture= $_FILES['picture']['name'];
$name= $_POST['name'];
$tmp= $_FILES['picture']['tmp_name'];
var_dump($picture);
var_dump($name);
var_dump($tmp);
$connect= mysqli_connect(//connect params)
or die('error connecting with the database');
$query= "INSERT INTO pics (pic, name) VALUES ('$picture', '$name')";
$target= GW_UPLOADPATH . $picture ;
if (move_uploaded_file($_FILES['picture']['tmp_name'], $target);))
{
mysqli_query($connect, $query)
or die('error with query');
}
?>

Your issue likely has something to do with php's upload_max_filesize and post_max_size. Check those 2 settings in your php.ini and make sure the file you are trying to upload isn't larger than either of them.

Related

MySQL insert stmt wont loop in file upload foreach loop

The code uploads the files and is supposed to submit the file path to the database so I can use the file paths elsewhere.
All the files upload fine in the loop, but for some reason, after it successfully submits the first MySQL stmt insert, it somehow bypasses the inserts that come after when it goes through the loop again, to upload the next file in the $_FILES[] superglobal
Here is the markup for the form
<?php
session_start();
include 'includes/functions.php';
drawHeader();
echo'
<div class="main_content_container">
';
if ( isset($_SESSION['userId'])) {
$amz_numb = $_GET['amz_numb'];
echo'
<form action="http://Localhost/Tierrashop.ca/includes/upload.php"
method="post" enctype="multipart/form-data">
Send these files
<input name="amz_numb" type="hidden"
value="'. $amz_numb .'"/><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<input name="file[]" type="file" /><br />
<button type="file">Upload Files</button>
</form>
<a href="http://localhost/Tierrashop.ca/content_upload.php">
<button>Go back to product details... </button></a>
';
} else {
echo '';
}
//close of main content div
echo '</div>';
drawFooter();
?>
PHP file that launches upon form submission
<?php
include 'config.php';
if (isset($_POST['amz_numb'])) {
$uploadlocation = "../product_images/";
$amz_numb = $_POST['amz_numb'];
// Count total files
$countfiles = count($_FILES['file']['name']);
// Looping all files
for ($i = 0; $i < $countfiles; $i++) {
$filename = $_FILES['file']['name'][$i];
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'][$i], $uploadlocation . $filename);
$directory_location = $uploadlocation . basename($filename);
chmod($directory_location, 0644);
//insert amz numb and path into db
$stmt = mysqli_prepare($conn, "INSERT INTO images ( amz_product_code, filepath )
VALUES (?,?)");
mysqli_stmt_bind_param($stmt, 'ss', $amz_numb, $directory_location);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($conn);
}
Take a look at this please:
https://www.php.net/manual/en/mysqli-stmt.close.php
The user contributed note might be helpful for your case:
"if you are repeating an statement in an loop using bind_param and so on inside it for a larger operation. i thougt id would be good to clean it with stmt->close. but it broke always with an error after aprox. 250 operations . As i tried it with stmt->reset it worked for me."
This might be the better option: https://www.php.net/manual/de/mysqli-stmt.reset.php
Or - much better - use PDO!
UPDATE: More on PDO
If you don't know how to use the more modern standard "PDO" (if I recall it correctly it stands for "PHP Data Objects") this should be really helpful. I used this myself to make my own database handler.
https://culttt.com/2012/10/01/roll-your-own-pdo-php-class/
The only caveat: The link above is a bit US centric. If you use it like that you will be in trouble if you support other languages in addition to English(US).
In //Define Configuration you should add:
define("DB_CHARSET", "utf8mb4");
Then in the database class itself you should add:
private $charset = DB_CHARSET;
"Set DSN" should consequently be modified like this:
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname . ';charset=' . $this->charset;
Apart from these minor changes the example is still very useful.
Yaaaaa, none of that resetting stuff helped.
Figured out you don't have to keep preparing the statement, however not sure if that's what was stopping it.
I had it uploading the file, than was preparing the stmt to then execute.
In the php.ini file I had:
max_file_uploads = 3, which explained why only three files were getting inserted and locking up the script in the loop.
Also I changed post_max_size = 150mb thinking that this allows all those files to be stored in the tmp_name key in the $_FILES superglobal

PHP cannot upload multiple images

I have a form in which I want to upload at most five images. The name and extension of the images are supposed to be inserted in the database table 'images' and then uploaded to the _uploads/name_of_the_album/ directory.
The problem is, when I choose some images and hit upload, only the first image is uploaded correctly, the other images fail.
Here is my code:
if(isset($_FILES['image']) === true){
$files = $_FILES['image'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$album_id = (int)$_GET['album_id'];
$album_name = $_GET['album_name'];
for($i=0; $i<count($files['name']); $i++){
$name = $files['name'][$i];
$tmp_name = $files['tmp_name'][$i];
$size = $files['size'][$i];
$ext = explode('.', $files['name'][$i]);
$ext = strtolower(end($ext));
$img_name = explode('.', $files['name'][$i]);
$img_name = strtolower(current($img_name));
//do some testing echos to see the result
//echo $img_name."<br>";
//here i'm going to add some validation as soon as
// i fix the multi-upload problem
//insert image into database
$query_insert_image = "INSERT INTO `images` (album_id, image_name, image_ext) VALUES ({$album_id}, '{$img_name}', '{$ext}') ";
$insert_image = mysql_query($query_insert_image, $connection) or die(mysql_error());
if(mysql_affected_rows() == 1){
move_uploaded_file($tmp_name, '../_uploads/'.$album_name.'/'.$name);
}
//redirect
redirect_to("view_album.php?succeed=1");
}//end the for loop
//echo '<pre>',print_r($files, true),'</pre>';
}
And here is some of the code of the form:
<form action="" method="post" enctype="multipart/form-data" name="formUploadImages" id="formUploadImages">
<p>
<label for="image">Choose one or more Image(s):</label><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" /><br />
<input type="file" name="image[]" id="image" />
</p>
......
Any ideas what I'm doing wrong?
I think you're cutting the branch from under your own feet.
redirect_to("view_album.php?succeed=1");
Redirecting means refreshing the page which means the end of execution. When that redirect is triggered after the first for loop ends and first image is uploaded the for will not continue to the next iteration.
And the fix of course is to push that line after the for loop (and never expect anything after a redirect to ever execute - unless the headers are already sent).
Most functions that do what redirect_to() does (it's not a core function it's based on another function header()) also make sure execution stops (have a line calling header() and another line calling die()/exit()).
try this php code ,working for me:
for($i=1;$i<6;$i++)
{
if(!empty($_FILES['image_upload'.$i])):
$target = "images/".$_FILES['image_upload'.$i]['name'];
$image_upload.= ",".mysql_real_escape_string(($_FILES['image_upload'.$i]['name']));
move_uploaded_file($_FILES['image_upload'.$i]['tmp_name'], $target);
endif;
}
create a folder in your root named "images" ,all the images will be moved in this folder.
html form may be looks like:
<form action="" method="post" enctype="multipart/form-data" name="formUploadImages" id="formUploadImages">
<p>
<label for="image">Choose one or more Image(s):</label><br />
<input type="file" name="image_upload1" id="image_upload1" /><br />
<input type="file" name="image_upload2" id="image_upload2" /><br />
<input type="file" name="image_upload3" id="image_upload3" /><br />
<input type="file" name="image_upload4" id="image_upload4" /><br />
<input type="file" name="image_upload5" id="image_upload5" />
</p>
......
this code is running on my end ,and after some editing as according to your needs may be useful for you.
Happy coding!
foreach($_POST['image'] as $report_id){
$sql="INSERT INTO images (album_id, image_name, image_ext) VALUES ('{$album_id}', '{$report_id}', '{$ext}') ";
$queryExe=mysql_query($sql);
}
replace this code in the place of your code after "//insert image into database" .
http://php.net/manual/en/features.file-upload.multiple.php
Read the Warning block 'Since PHP 5.2.12, the max_file_uploads configuration...'. Maybe that's the problem.
And there are some good examples and maybe You should use foreach instead of for.
1) Create a .htaccess file in the root folder of web server.
2) Put the following code in side the .htaccess file and save it.
php_value upload_max_filesize 20M
php_value post_max_size 20M
php_value max_execution_time 200
php_value max_input_time 200
Now you can upload the file-size up-to 20MB in a simple way using file field in your html form and move_uploaded_file() function available in PHP.

move uploaded file in PHP

I want to allow a user the upload an image (file) for their profile picture, on my website. They upload the image via an HTML form, but I am having trouble moving the file to the folder I want it to. I don't want to mess with the php.ini file to change the upload path. I want to use move_uploaded_file().
Here is my HTML:
<form enctype="multipart/form-data" method="post" action="upload_img.php">
<input type="hidden" name="MAX_FILE_SIZE" value="32768"/>
<input type="text" name="name" value=""/>
<input type="file" name="picture" value="picture"/>
<input type="submit" name="submit" value="upload"/>
</form>
And my PHP:
<?php
define('GW_UPLOADPATH', 'images/');
$picture= $_FILES['picture']['name'];
$name= $_POST['name'];
$tmp= $_FILES['picture']['tmp_name'];
var_dump($picture);
var_dump($name);
var_dump($tmp);
$connect= mysqli_connect(//connect params)
or die('error connecting with the database');
$query= "INSERT INTO pics (pic, name) VALUES ('$picture', '$name')";
$target= GW_UPLOADPATH . $picture ;
if (move_uploaded_file($_FILES['picture']['tmp_name'], $target);))
{
mysqli_query($connect, $query)
or die('error with query');
}
?>
I know the file gets uploaded to the tmp folder because I can see it, but it is named sess_96bsj29ub3tndnd2853d24k38adrbqoo.file Is that what should happen? What am I doing wrong?
$_FILES['picture']['tmp_name']
will point the file in that folder and when you call this line
move_uploaded_file($_FILES['picture']['tmp_name'], $target);
you'd get the file in your temp folder to wherever you want. just set $target to be a valid and existing directory.
Just remove semicolon form if statement like:
if (move_uploaded_file($_FILES['picture']['tmp_name'], $target)))
{
mysqli_query($connect, $query)
or die('error with query');
}

Image Upload & storing the link in the database

I'm using this form to add the title,link of the image and the text of the article to the database.
I'm using type="text" for the image link,now,it's getting borring to upload an image on a external image upload service and copy the link.
I want to upload the image with this for and store THE LINK of the image in the database.
The form:
<?php if (!$_POST["go"]){ ?>
<form method="post" action="">
<input name="article_title" type="text">
<input name="article_image_url" type="text"> <!-- i want here type="file" -->
<textarea name="article_text"></textarea>
<input type="submit" name="go" value="Submit">
</form>
<?php
} else {
$date=date("Y.m.d");
$title = $_POST["article_title"];
$image_url = $_POST["article_image_url"];
$text = $_POST["text"];
$sql="INSERT INTO articles (title,image_url,text,date) VALUES ('$title', '$image_url', '$text', '$date')";
if (mysql_query($sql)){
echo "done";}
else {echo "error<br>" . mysql_error();}}
?>
Please help me with this :)
ps:sorry for my English :$
The first thing you should do, and it seems you are clueless about SQL escaping, is add following before you access the first $_POST var:
$_POST = array_map("mysql_real_escape_string", $_POST);
Then you seemingly want to use a file upload for the image. If so change the url field to:
<input type=file name=image>
This uploaded file will show up in $_FILES. Use it like this, preferrably after you've read the other fields from $_POST:
if ($img = $_FILES["image"]["tmp_name"]) {
$image_url = md5_file($img) . ".jpeg";
move_uploaded_file($img, "./upload/$image_url");
$image_url = "http://www.example.org/where/$image_url";
}
There are lot's of security concerns with that. But that's out of scope here, so I hardwired it to .jpeg. There's lots of information in the manual and its comments: http://de2.php.net/manual/en/features.file-upload.php

How do I edit form and script to upload two files instead of one -file to server, file name to mysql

The form and PHP code included here has been used to successfully upload a file name to the database and the file itself to a folder on the server. I need to edit the form and the code to allow for simultaneous upload of two files instead of just one. The filenames will go to the database while the files themselves will go to a folder on the server. In the mysql database fields each of the filenames have to be proceeded with static strings thusly; "images/" and "flash/". The one for images is that way already in the script, I just need to amend the script to accept a second file upload (the files uploaded will be jpeg and flash instead of just jpeg the way it is now. On the form the second file field could carry the name Flash. I have edited the mysql database so it will have an additional field named "flash".
In short, I need this to work exactly ad it does now, only uploading 2 files instead of one. How do i do this?
<form enctype="multipart/form-data" action="add.php" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
STK: <input type="text" name = "STK"><br>
<input type="submit" value="Add">
</form>
</body>
</html>
<?php
//This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$ID=$_POST['ID'];
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$pic=($_FILES['photo']['name']);
$STK=$_POST['STK'];
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("employees") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `employees` VALUES ('$ID','$name', '$email', '$phone', 'images/$pic','$STK')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
</body>
first of all the form needs to be changed:
Photo 1: <input type="file" name="photo[]"><br>
Photo 2: <input type="file" name="photo[]"><br>
second:
you would a: need another field in your database to store the second photo file name
then just use a foreach() loop to run through the $_Files array
If you want to separate the photos from the Flash files, you would change your form like so:
Photo: <input type="file" name="photo"><br />
Flash file: <input type="file" name="flash"><br />
and then add:
$pic=($_FILES['photo']['name']);
$flash=($_FILES['flash']['name']);
And finally add to your INSERT query accordingly. Like sfmoe said, if you want to allow multiple photos and multiple flash files, just add more fields, turn photo and flash into photo[] and flash[] (in the input tags), and use a foreach loop.

Categories