Unable to share PHP variable - php

I am having trouble sharing a variable value between my main body of code and as function.
For this example, I want to upload an image to the DB with a value which matches the ID of the Place being used.
I currently grab the ID of the place being used from the URL using $_REQUEST and am attempting to write that to a variable 'mid' which I then send to the createthumnail function (contained in functions2.php), but the 'mid' value will not transfer for some reason.
To recreate:
Go to: http://www.students.bl.rdi.co.uk/stu26984/index.php
Login with: Username: Test Password: test123
Go to My Places
Click on WalkaboutSF link
Attempt to upload a file via the 'Choose File' button
Below is the full text of functions2.php
<?php
function createThumbnail2($filename, $mid) {
include 'base.php';
require 'config.php';
if(preg_match('/[.](jpg)$/', $filename)) {
$im = imagecreatefromjpeg($path_to_image_directory . $filename);
} else if (preg_match('/[.](gif)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}
imagejpeg($nm, $path_to_thumbs_directory . $filename);
// $cookieUserx=$_SESSION['Username'];
// $checkCustidx=mysql_query("SELECT custid AS id from customers WHERE custUsername='".$cookieUserx."';");
// $rx=mysql_fetch_array($checkCustidx);
// $custidx=$rx['id'];
// $updateimage = mysql_query("UPDATE photos SET name = '".$filename."';")or die ('SQL Error: ' . mysql_error());
$updateimage = mysql_query("INSERT INTO photos (NAME, markerid) VALUES('".$filename."', '".$mid."');")or die ('SQL Error: ' . mysql_error());
if($updateimage)
{
header("Location: /WalkaboutSF/viewplace.php?place_id=%20".$mid."");
}
else
{
echo "<h1>Error</h1>";
}
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
echo $tn;
}
?>
also here is the code that calls that, from:
http://www.students.bl.rdi.co.uk/stu26984/viewplace.php?place_id=%20133
<div id="insertphoto">
<?php
require 'config.php';
require 'functions2.php';
$place_id = $_REQUEST['place_id'];
$view_place2 = mysql_query("SELECT * FROM markers WHERE id = '$place_id'");
$place2 = mysql_fetch_array($view_place2);
$mid= $place2['id'];
echo $mid;
if(isset($_FILES['fupload'])) {
if(preg_match('/[.](jpg)|(gif)|(png)$/', $_FILES['fupload']['name'])) {
$filename = $_FILES['fupload']['name'];
$source = $_FILES['fupload']['tmp_name'];
$target = $path_to_image_directory . $filename;
move_uploaded_file($source, $target);
createThumbnail2($filename, $mid);
}
}
?>
<h2>Add Photo</h2>
<form enctype="multipart/form-data" action="<?php print $_SERVER['PHP_SELF'] ?>" method="post">
<input type="file" name="fupload" />
<input type="submit" value="Go!" />
</form>
</div>

There are a few things that could be going on. Firstly:
$place2 = mysql_fetch_array($view_place2);
$mid= $place2['id'];
echo $mid;
Are you certain that $mid is being set here? Is it possible that the query returned no rows?
If you're sure it has a value here, then check this:
function createThumbnail2($filename, $mid) {
include 'base.php';
require 'config.php';
Are you sure that base.php or config.php are not overwriting the value of $mid? Try changing the code to this:
function createThumbnail2($filename, $mid) {
echo "mid before includes = $mid<br />\n";
include 'base.php';
require 'config.php';
echo "mid after includes = $mid<br />\n";
That will show you if your includes are stomping on your local variables.
edit: I didn't want to sidetrack the question, but your code is open to SQL injection. I could easily wipe your database by calling viewplace.php with a bad value. At the very least, do this:
$place_id = mysql_real_escape_string($_REQUEST['place_id']);
Your insert statement has the same issue. Look into using mysqli or PDO with prepared statements.
edit 2: The reason your code is not working is because there are 2 different HTTP requests working here: one to show the initial page and one to handle the POST to the upload form.
The issue is with the second request (the POST). This code is to blame:
<form enctype="multipart/form-data" action="<?php print $_SERVER['PHP_SELF'] ?>" method="post">
This is NOT passing the ID in $_REQUEST['place_id']. Just add this line below that one:
<input type="hidden" name="place_id" value=<?php echo HtmlspecialChars($_REQUEST['place_id']); ?>" />
This will pass the place_id to the second request, when the form is submitted.

Related

Uploading multiple images to MySql database

I am trying to upload multiple images for a product for an eCommerce website. The idea is to save the service name in the services table while the images are saved in the service_images table, but whenever I run the php file, it uploads the service to the services table but only uploads one image to the service_images table instead of all the images. How can I get it to upload one service in the services table and also multiple images of that one service in the service_images table?
Below is my code:
add-service.inc.php
<?php
if (isset($_POST['add-service'])) {
require 'config.php';
$shop_name = mysqli_real_escape_string($conn, $_POST['shop_name']);
$service_cat = mysqli_real_escape_string($conn, $_POST['service_cat']);
$service_name = mysqli_real_escape_string($conn, $_POST['service_name']);
$service_desc = mysqli_real_escape_string($conn, $_POST['service_desc']);
$service_price = mysqli_real_escape_string($conn, $_POST['service_price']);
$service_type = mysqli_real_escape_string($conn, $_POST['service_type']);
$service_images = $_FILES['service_images'];
if (empty($shop_name) || empty($service_cat) || empty($service_name) || empty($service_desc) || empty($service_price) || empty($service_type)) {
header('Location: ../services.php?error=emptyFields');
exit();
} elseif (!preg_match('/^[a-zA-Z0-9]*$/', $shop_name) && !preg_match('/^[a-zA-Z0-9\s]*$/', $service_name) && !preg_match('/^[a-zA-Z0-9\s \. \-]*$/', $service_desc) && !preg_match('/^[0-9\.]*$/', $service_price) && !preg_match('/^[a-zA-Z0-9\s \.]*$/', $service_type)) {
header('Location: ../services.php?error=invalidInputs');
exit();
} elseif (!preg_match('/^[a-zA-Z0-9]*$/', $shop_name)) {
header('Location: ../services.php?error=invalidShopName');
exit();
} elseif (!preg_match('/^[a-zA-Z0-9\s]*$/', $service_name)) {
header('Location: ../services.php?error=invalidserviceName');
exit();
} elseif (!preg_match('/^[a-zA-Z0-9\s \. \-]*$/', $service_desc)) {
header('Location: ../services.php?error=invalidDescription');
exit();
} elseif (!preg_match('/^[0-9\.]*$/', $service_price)) {
header('Location: ../services.php?error=invalidPrice');
exit();
} elseif (!preg_match('/^[a-zA-Z0-9\s \.]*$/', $service_type)) {
header('Location: ../services.php?error=invalidStyle');
exit();
} else {
foreach ($_FILES["service_images"]["tmp_name"] as $key => $tmp_name) {
$file_name = $_FILES["service_images"]["name"][$key];
$file_type = $_FILES["service_images"]["type"][$key];
$file_tempName = $_FILES["service_images"]["tmp_name"][$key];
$file_error = $_FILES["service_images"]["error"][$key];
$file_size = $_FILES["service_images"]["size"][$key];
$a = count($_FILES['service_images']['name']);
for ($i = 0; $i < $a; $i++) {
$fileExt = explode('.', $file_name);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'png', 'jpeg');
if (in_array($fileActualExt, $allowed)) {
if ($file_error === 0) {
if ($file_size <= 15000000) {
$newFileName = preg_replace('/\s+/', '', $service_name) . $i . '.' . $fileActualExt;
echo $newFileName . "<br>";
$fileDestination = '../../services/' . $newFileName;
$sql_images = "INSERT INTO service_images (shop_name, service_name) VALUES ('$shop_name', '$service_name')";
$result = mysqli_query($conn, $sql_images);
$sql = "INSERT INTO services (shop_name, service_cat, service_name, service_desc, service_price, service_type) VALUES (?,?,?,?,?,?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../services.php?error=SaveError");
exit();
} else {
mysqli_stmt_bind_param($stmt, 'ssssss', $shop_name, $service_cat, $service_name, $service_desc, $service_price, $service_type);
mysqli_stmt_execute($stmt);
// move_uploaded_file($file_tempName = $_FILES["service_images"]["tmp_name"][$i], $fileDestination);
header("Location: ../services.php?success");
exit();
}
} else {
header('Location: ../services.php?error=invalidSize');
exit();
}
} else {
header('Location: ../services.php?error=invalidImage');
exit();
}
} else {
header('Location: ../services.php?error=invalidImageType');
exit();
}
}
}
}
}
form
<form action="../admin/includes/add-service.inc.php" method="post" enctype="multipart/form-data">
<input type="text" name="shop_name" id="shopName" class="form-input" placeholder="Shop Name">
<select name="service_cat" id="serviceCat" class="form-input">
<option> -- select category -- </option>
<?php
$sql = "SELECT * FROM service_category";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $row['service_cat'] ?>"><?php echo $row['service_cat'] ?></option>
<?php
}
}
?>
</select>
<input type="text" name="service_name" id="serviceName" class="form-input" placeholder="Service Name">
<textarea name="service_desc" id="service_desc" cols="1" rows="5" placeholder="Description" class="form-input"></textarea>
<input type="text" name="service_price" id="servicePrice" class="form-input" placeholder="Service Price">
<input type="text" name="service_type" id="serviceType" class="form-input" placeholder="Service Type">
<hr>
<label for="serviceImages">*Select all pictures for your service</label>
<input type="file" name="service_images[]" id="serviceImages" class="form-input" multiple>
<button type="submit" class="btn-add" name="add-service">Add Service</button>
</form>
First of all, you have the same loop twice. First as foreach and then as for. Since you need numeric keys from this weird array type of $_FILES, then your best approach is to use for loop only.
These double loops are already so messy, that could cause unexpected issues, if one of the files has a problem for example.
But, your main issue is, that you are basically checking only one image and then uploading it. If the validation process or success goes trough, it has exit(); at the end. It kills not only the loop, but the entire script. You are not allowing the second image loop to continue, as first one kills it.. either on success or error.
Solution would be to wait for the loops to finish (adding code after the loops brackets) and putting the success related code there. If an error is detected inside the loops, then the script never gets that far.
I have no idea, how you are actually linking the images to service, but I tried to clean up your code and make the order correct. I also did my best at explaining why and where. Hopefully, you understand the problem better from this or even better, find better options to optimise your code:
// TESTING: Lets see what is inside post values:
echo '<b>$_POST values</b><pre>'; print_r($_POST); echo '</pre>';
// TESTING: Lets see what is inside the files values:
echo '<b>$_FILES values</b><pre>'; print_r($_FILES); echo '</pre>';
// Above is for testing only..
// Probably better place to load important configs:
require 'config.php';
// Since these are the conditions for uploads, then they are global:
// no need for them to be inside the loop:
$allowed = array('jpg', 'png', 'jpeg');
// Maximum allowed filesize:
$max_allowed_file_size = 15000000; // which is 15mb
// We detect the submit buttons trigger name:
if (isset($_POST['add-service'])) {
// Do the escape thingy:
// NOTE: You should be using some mysqli class for database handling:
$shop_name = mysqli_real_escape_string($conn, $_POST['shop_name']);
$service_cat = mysqli_real_escape_string($conn, $_POST['service_cat']);
$service_name = mysqli_real_escape_string($conn, $_POST['service_name']);
$service_desc = mysqli_real_escape_string($conn, $_POST['service_desc']);
$service_price = mysqli_real_escape_string($conn, $_POST['service_price']);
$service_type = mysqli_real_escape_string($conn, $_POST['service_type']);
$service_images = $_FILES['service_images'];
// Lets deal with the errors before going forward with the rest of the script:
// You don't need elseif here, because your callback is to redirect and exit anyways..
if (empty($shop_name) || empty($service_cat) || empty($service_name) || empty($service_desc) || empty($service_price) || empty($service_type)) {
header('Location: ../services.php?error=emptyFields');
exit();
}
if (!preg_match('/^[a-zA-Z0-9]*$/', $shop_name) && !preg_match('/^[a-zA-Z0-9\s]*$/', $service_name) && !preg_match('/^[a-zA-Z0-9\s \. \-]*$/', $service_desc) && !preg_match('/^[0-9\.]*$/', $service_price) && !preg_match('/^[a-zA-Z0-9\s \.]*$/', $service_type)) {
header('Location: ../services.php?error=invalidInputs');
exit();
}
if (!preg_match('/^[a-zA-Z0-9]*$/', $shop_name)) {
header('Location: ../services.php?error=invalidShopName');
exit();
}
if (!preg_match('/^[a-zA-Z0-9\s]*$/', $service_name)) {
header('Location: ../services.php?error=invalidserviceName');
exit();
}
if (!preg_match('/^[a-zA-Z0-9\s \. \-]*$/', $service_desc)) {
header('Location: ../services.php?error=invalidDescription');
exit();
}
if (!preg_match('/^[0-9\.]*$/', $service_price)) {
header('Location: ../services.php?error=invalidPrice');
exit();
}
if (!preg_match('/^[a-zA-Z0-9\s \.]*$/', $service_type)) {
header('Location: ../services.php?error=invalidStyle');
exit();
}
// Nothing happened above, so that means the form validation should be fine and we can go forward with the images:
// So as in your script, we count the images:
$a = count($_FILES['service_images']['name']);
// Now we do a "numeric loop", not an array loop, which is foreach:
for ($i = 0; $i < $a; $i++) {
// Since we have the key as numeric now, we can do what you did before, but without the foreach loop:
$file_name = $_FILES['service_images']['name'][$i];
$file_type = $_FILES['service_images']['type'][$i];
$file_tempName = $_FILES['service_images']['tmp_name'][$i];
$file_error = $_FILES['service_images']['error'][$i];
$file_size = $_FILES['service_images']['size'][$i];
// Get the file extension:
// NOTE: This is not good, as you should really check the mime type of the file, not the extension.
$fileActualExt = strtolower(end(explode('.', $file_name)));
// TESTING: We check print out the data to make sure, that all looks fine:
echo 'File with the key: ' . $i .' -- $file_name: ' . $file_name . '; $file_type: ' . $file_type . '; $file_tempName: ' . $file_tempName . '; $file_error: ' . $file_error . '; $file_size: ' . $file_size . '<br>';
// Instead of making the code ugly, lets deal with errors, by killing the script before
// NOTE: This is not good approach, you should be using Exceptions:
// https://www.php.net/manual/en/language.exceptions.php
// Check if the file extension is NOT in the allowed array
if (!in_array($fileActualExt, $allowed)) {
// Redirect:
header('Location: ../services.php?error=invalidImageType');
// Kill the script:
exit('invalidImageType');
}
// Check if the file had an error:
if ($file_error) {
// Redirect:
header('Location: ../services.php?error=invalidImage');
// Kill the script:
exit('invalidImage');
}
// Check if the image bytes are BIGGER > then max allowed file size variable:
if ($file_size > $max_allowed_file_size) {
// Redirect:
header('Location: ../services.php?error=invalidSize');
// Kill the script:
exit();
}
// At this stage, hopefully, there has not been any errors above and we can deal with file freely:
// Make new file name:
$newFileName = preg_replace('/\s+/', '', $service_name) . $i . '.' . $fileActualExt;
// echo $newFileName . "<br>";
// Set the new destination:
$fileDestination = '../../services/' . $newFileName;
// Lets move the file already.
// NOTE: Make sure that you have some bash code from server side, that deletes outdated / old temp files, so they dont take space:
move_uploaded_file($file_tempName = $_FILES["service_images"]["tmp_name"][$i], $fileDestination);
// Insert the image to database:
// NOTE: Im not sure about your specific code, but just this is there location for that:
$sql_images = "INSERT INTO service_images (shop_name, service_name) VALUES ('$shop_name', '$service_name')";
$result = mysqli_query($conn, $sql_images);
// PROBLEM: This is where you originally had the success message redirect and exit.
// This means, you KILL the script and there for the loop.
// But you have to understand, that you have two images or more, so the loop has to continue freely,
// and you can do this sort of stuff at after the loop!
//
// header("Location: ../services.php?success");
// exit();
}
// If nothing happened above, then the image uploads went trough nicely and we can deal with success messages or adding the service itself:
// I have not used mysqli stmpt before, so I have no idea what is going on in this area..:
// .. but this the locatin to deal with the services as this is the parent and the children are above.
$sql = "INSERT INTO services (shop_name, service_cat, service_name, service_desc, service_price, service_type) VALUES (?,?,?,?,?,?)";
$stmt = mysqli_stmt_init($conn);
// I don't think you need this at all, but whatever:
// Shouldnt this be above
if (!mysqli_stmt_prepare($stmt, $sql)) {
// Redirect:
header("Location: ../services.php?error=SaveError");
// Kill the script:
exit();
}
// This is adding the service I assume, it has to be outside the loop, as single submit = single service. But images are multiple.
mysqli_stmt_bind_param($stmt, 'ssssss', $shop_name, $service_cat, $service_name, $service_desc, $service_price, $service_type);
mysqli_stmt_execute($stmt);
// This is where you can have the success redirect and exit, as this is after the loop:
header("Location: ../services.php?success");
exit();
}
NOTES:
You should be using Exceptions for your error handling.
Learn the difference between foreach and for loops.
File extensions can be tricked, check out the file mime type instead
Allowed file types array inside the loop is not very smart, as you will use it it more than once in all the loop cycles. Best to keep it at the top of the script, so its easier to setup in the future. Same goes for the filesize variable.
It would make alot more sense to detect the file types, sizes via javascript before they even get to your server. This way you save temp file folder space issues and bandwidth basically.
I don't understand where you actually use $result from the mysql. Or where do you link the images from service_images table to the actual service.
Use <input type="file" name="service_images[]" multiple accept=".jpg, .png, .jpeg"> (the multiple accept=".jpg, .png, .jpeg") in the form to not allow the user to pick any other extensions. You can also use "images" value for all images.

Upload process don't save the right name in database

I have a code in php with validation ok all working properly but my problem is that when I try to save in database I obtain something like this:
img_id img_small img_big
5 /tmp/phpdlYkiG /tmp/phph3dhka
I don't know why php save that name because the images have a diffent names like koala.jpg and horse.jpg
Here is my code in order to see if somebody have any suggestion...
<form enctype="multipart/form-data" action="upload_type_1.php" method="POST" >
<input type="file" name="img_small_1" id="img_small_1">
<input type="file" name="img_big_1" id="img_big_1">
<input type="submit" value="Upload" name="submit">
</form>
and this is my php code:
if ( (move_uploaded_file($_FILES["img_small_1"]["tmp_name"], $target)) && (move_uploaded_file($_FILES["img_big_1"]["tmp_name"], $target2)) ){
$img_title_1 = $_POST['img_title_1'];
$sql = "INSERT INTO press (img_title, img_small, img_big) VALUES ('$img_title_1', '$img_small_1', '$img_big_1')";
$retval = mysql_query( $sql, $conn );
if(!$retval) {
die('Could not enter data: ' . mysql_error());
}
mysql_close($conn);
echo "Your files has been uploaded";
} else {
echo "Sorry, there was an error uploading your files.";
exit;
}
This code work properly the only problem is that save into database that strange names and I need to use that names...
Thanks! - Waiting for help!
Your issue is probably not in the code that you are showing but in the code you are not showing, which is your variable declarations for $img_small_1 && $img_big_1. Taking a guess you have
$img_small_1 = $_FILES["img_small_1"]["tmp_name"];
$img_big_1 = $_FILES["img_big_1"]["tmp_name"];
but you want/need
$img_small_1 = $_FILES["img_small_1"]["name"];
$img_big_1 = $_FILES["img_big_1"]["name"];
$img_title_1 = $_POST['img_title_1'];
Should be:
$img_title_1 = $_FILES["img_small_1"]["name"]
A Simple Example of File Uploading
$uploadDir = "Your_upload_dir";
$img_small = $_FILES['img_small_1'];
$img_small_name = $img_small['name']; // get image name
$img_small_tmpName = $img_small['tmp_name'];
$img_small_fileSize = $img_small['size'];
$img_small_fileType = $img_small['type'];
if ($img_small['error'] == 0)
{
$img_small_filePath = $uploadDir . $img_small_name;
$result = move_uploaded_file($img_small_tmpName, img_small_filePath); //return true or false
}

Why Image Uploads to folder but not insert into mysql DB?

Hi Guys i got a Problem i upload an image to Upload Folder upload is working fine but he dont submit the value into mysql database and i really dont know where the failure ist here ist the whole code.
Unique Value is id from the user and the field for the image name is company_logo.
My dashboard code:
The Form:
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
<input type="file" name="photoimg" id="photoimg" />
</form>
JQuery Code
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').on('change', function() {
$("#preview").html('');
$("#preview").html('<div class="spinner"></div>');
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
And Finally The ajaximage.php
<?php
session_start();
ob_start();
$valid_user_id = trim($_SESSION["VALID_USER_ID"]);
if(isset($_SESSION["VALID_USER_ID"]) && !empty($valid_user_id))
{
include "database_connection.php"; //Include the database connection script
//Check the logged in user information from the database
$check_user_details = mysql_query("select * from `signup_and_login_table` where `email` = '".mysql_real_escape_string($_SESSION["VALID_USER_ID"])."'");
//Get the logged in user info from the database
$get_user_details = mysql_fetch_array($check_user_details);
//Pass all the logged in user info to variables to easily display them when needed
$user_id = strip_tags($get_user_details['id']);
$firstname = strip_tags($get_user_details['firstname']);
$lastname = strip_tags($get_user_details['lastname']);
$company = strip_tags($get_user_details['company']);
$company_logo = strip_tags($get_user_details['company_logo']);
$email = strip_tags($get_user_details['email']);
$passwd = strip_tags($get_user_details['password']);
// User Id for Image Upload
$session_id = strip_tags($get_user_details['id']);
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysqli_query($db,"UPDATE signup_and_login_table SET company_logo='$actual_image_name' WHERE id='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
}
else
{
//Send every user who tries to access this page directly without valid session to the login page.
//The login page is the door that every user needs to pass to this page
header("location: login.html");
}
?>
Use the following sql query:
INSERT INTO signup_and_login_table (company_logo, id) VALUES ('$actual_image_name', '$session_id')
You've made instead a UPDATE Query, which only updates already EXISTING rows.
Kind regards!
Try this query
mysqli_query($db,"UPDATE signup_and_login_table SET company_logo='$actual_image_name' WHERE id=".$session_id);

Having error in saving image link to the database using pdo [duplicate]

This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
I want to do is make a image uploader system and send the image to upload folder and save the link to the database.
My problem is I got this to errors in my images.php can anyone help me with this please.
html:
<form method="post" enctype="multipart/form-data">
<img id="picture" data-src="#" /> <br />
<input type='file' name="image" id="imgInp" accept="image/*" /><br />
<input type="submit" name="submit" id="submit" value="submit" />
</form>
script:
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function (e) {
e.preventDefault();
var data = {};
data.image = $('#imgInp').val();
$.ajax({
type: "POST",
url: "images.php",
data: data,
cache: false,
success: function (response) {
}
});
return false;
});
});
</script>
images.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$image = addslashes(file_get_contents(#$_FILES['image']['tmp_name']));
$image_name = addslashes(#$_FILES['image']['name']);
$image_size = getimagesize(#$_FILES['image']['tmp_name']);
move_uploaded_file(#$_FILES["image"]["tmp_name"], "upload/" . #$_FILES["image"]["name"]);
$location = "upload/" . #$_FILES["image"]["name"];
$q = "INSERT INTO students( image ) VALUES( :image)";
$query = $dbc->prepare($q);
$query->bindParam(':image', $location);
$results = $query->execute();
?>
script for image upload:
<script type="text/javascript">
$(document).ready(function() {
var currentSrc = $('#picture').attr('src');
if(currentSrc==null || currentSrc==""){
$('#picture').attr('src','http://i38.photobucket.com/albums/e149/eloginko/profile_male_large_zpseedb2954.jpg');
$("#picture").on('click', function() {
$("#imgInp").trigger('click')}
)}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#picture').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
});
</script>
The simplest thing to get rid of the error messages is to actually place a conditional that checks if $_FILES has anything in it. But past that, unclear on the root cause of $FILES being empty. In my experience Ajax file uploading with a PHP receiver on the other side just doesn’t work consistently at best. Anyway, here is my version of your code with a conditional in place:
if (!empty($_FILES)) {
$image = addslashes(file_get_contents(#$_FILES['image']['tmp_name']));
$image_name = addslashes(#$_FILES['image']['name']);
$image_size = getimagesize(#$_FILES['image']['tmp_name']);
move_uploaded_file(#$_FILES["image"]["tmp_name"], "upload/" . #$_FILES["image"]["name"]);
$location = "upload/" . #$_FILES["image"]["name"];
$q = "INSERT INTO students( image ) VALUES( :image)";
$query = $dbc->prepare($q);
$query->bindParam(':image', $location);
$results = $query->execute();
}
Try this approach, it might look like too many if statement, but you need to have checks if you want solid code:
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$folder = "upload/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) {
echo "succesful upload, we have an image!";
//PDO
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "INSERT INTO students( image ) VALUES( :image)";
$stmt = $dbc->prepare($query);
$stmt->bindParam(':image', $full_path);
$results = $stmt->execute();
if($results){
echo "Insert successful!";
}else{
echo "Insert failed!";
}
} else {
echo "upload received! but process failed";
}
}else{
echo "upload failure ! Nothing was uploaded";
}
Few things I would like to point out:
# suppress error, you don't want that when you troubleshoot, even in
production, you still want to be aware of the error.
You should enable error reporting
You didn't check if php script receives the image upload.
The use of file_get_contents is unclear in this case
You don't make use of the $image* variables ? ....

Why do I get this error when trying to upload an image?

When I go to myserver index and upload and image from there using the interface, it works fine. But as soon as I try to enter the path myself, like:
http://myserver/upload.php?image['name']=F:\Bilder\6.jpg
it gives me an error that all fields are required. But I have to upload images like this, because I plan to implement it in an app that I'm making. Thing is, that I'm not that well acquainted with php.
here is the upload.php
<?php
session_start();
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/";
$image = $_FILES['image'];
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: index.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: index.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: index.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Avatar (filename) values ('" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
exit;
}
else
{
header("Location: index.php");
exit;
}
?>
and the index.php
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>
<label>Avatar</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="submit" id="submit" value="Upload" />
</p>
the problem lies in
if ( $image['name'] == "" )
$image has no value there.
You are doing a get request so if you would like to know what the image variable is you should use
$_GET['image']
Another thing is that you are doing $image = $_FILES['image'];
$_FILES will only be available from a post request.
Uploading files can not be done in the way you are doing now by a parameter from a GET request.
If you need to POST stuff to a web form (as opposed to GETting, which is what you're doing here), you can't just specify the data to be POSTed as part of the URL.
Have a look at those HTTP methods (GET and POST) to understand the difference.
In your app, what you need to do is POST stuff to the URL. Depending on which tools you use to program, you should look into how to send data via POST.
Also, try to see if an implementation of curl (or libcurl) is available to your development platform.
That simply wont work since you cannot upload an image by sending $_GET[] variables through the url.
As you can see in the upload.php page you got, the file is retrieved in the php page through a $_FILES['image'].
If you change that to $_GET['image'] and retry to post the link with the get variable you suggest, you probably will be able to see the path to your file but it will only be as a string type and not an actual uploaded file object.

Categories