what i want to do is to upload image to the server using php
this is my code
<?php
try {
$name = isset($_POST['variable2']);
$file = rand(1000,100000)."-".isset($_FILES['file']['name']);
$file_name = isset($_FILES['file1']['name']);
$file_loc = isset($_FILES['file1']['tmp_name']);
$file_size = isset($_FILES['file1']['size']);
$file_type = isset($_FILES['file1']['type']);
$folder="uploads123/";
$new_size = $file_size/1024;
$new_file_name = strtolower($file);
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
echo "good";
}else{
echo "error";
}
} catch (PDOException $pe) {
die("Error occurred:" . $pe->getMessage());
}
?>
these are my problems
why is it that the output it just the "error" from the if statement? it doesn't give details about the error even if i'm using try and catch.
even if i give a wrong foldername(the directory where the image to be uploaded) it just give me output like "error" from the if statement.
it doesn't give error that the folder doesn't exist on the server.
thank you.
Your html form is like that?
<form action="target.php" enctype="multipart/form-data">
<!-- Content -->
</form>
Does folder exists? check privilegies on server for folder
Good way before move file:
$upload_dir = '/uploads123';
if(!is_dir($upload_dir)){
mkdir($upload_dir, 0777); // you may set your access rule
}
Then you can try move file to this dir
EDIT: Try changing PDOException to Exception
isset() returns a boolean (true or false)
$file_loc will not be a valid file location, but is a boolean:
$file_loc = isset($_FILES['file1']['tmp_name']); // $file_loc = true
move_uploaded_file wil fail as it has no valid file to move and returns false. Your code will echo "error" as a result of move_uploaded_file returning false.
There is no Exception thrown, let alone a PDOException.
Related
I'm really struggling with an issue relating the move_uploaded_file function of php.
The path should be correct, but see yourself:
$imgDir = "../img/".$CATEGORY;
$fileName = $_FILES['image']['name'];
$maxsize = 800;
$compQuality= 75;
if(!is_dir($imgDir)) {
mkdir($imgDir.'/tn', 0777, true);
chmod($imgDir, 0777);
chmod($imgDir, 0777);
}
$imgDir = $imgDir."/";
$imgTnDir = $imgDir."tn/";
I have also tested it by echo-ing everything and it seems to work, but when it comes to the move_uploaded_file it still does not work, even though I test if the file really exists:
if(file_exists($imgDir.$fileName)) {
$status = "The file ".$fileName." already exists, please choose a different title.";
}
if(!move_uploaded_file($_FILES['image']['tmp_name'], $imgDir.$fileName)) {
$status = "File upload failed, sorry.";
}
if(!empty($status)) {
echo $status;
exit();
}
I hope that someone can help me. If you want I can print anything out you need or give you more snippets of the code. The var $_FILES['image']['tmp_name'] does not only exist, but has a proper name by the way.
Also I have checked the php.ini and both uploading is allowed and the size is surely set high enough.
Thank you in advance.
make sure that you have the right path in $imgDir. You can try:
if(!is_writable($imgDir)) { exit('CANNOT_WRITE_IN_DIR'); }
and also you can use an absolute path, like this:
$imgDir = __DIR__ . "/../img/".$CATEGORY;
On my website, I allow users to submit files and they are sent to the database and a file directory, devFiles, I created. It sends to the database fine, but when i send it to the directory, it never sends and i get my error message i created to see if it sends or not. I believe the problem is with the
if(is_file($dir.'/'.$file_name)==false){
//code...
}
but i tried change the condition but it didn't work. So what i want to do is, send the file that was submitted to the file directory on hand that was created. Here is my code
PHP
$query = "INSERT INTO pack_screenshots(pack_id, file_name, file_tmp)VALUES(:packid, :file_name, :file_tmp)";
$stmtFileUpload = $handler->prepare($query);
$errors = array();
foreach($_FILES['file']['tmp_name'] as $key => $error){
if ($error != UPLOAD_ERR_OK) {
$errors[] = $_FILES['file']['name'][$key] . ' was not uploaded.';
continue;
}
$file_tmp = file_get_contents($_FILES['file']['tmp_name'][$key]);
$file_name = addslashes(trim($_FILES['file']['name'][$key]));
try{
$stmtFileUpload->bindParam(':packid', $packid, PDO::PARAM_STR);
$stmtFileUpload->bindParam(':file_name', $file_name, PDO::PARAM_STR);
$stmtFileUpload->bindParam(':file_tmp', $file_tmp, PDO::PARAM_STR);
$dir = "devFiles";
if(is_dir($dir)==false){
mkdir($dir, 0700);
}
if(is_file($dir.'/'.$file_name)==false){
if(!move_uploaded_file($file_tmp,$dir.'/'.$file_name)){
die("File didn't send!");
}
}else{
$_SESSION['invalid'] = true;
header("Location: developer_invalid.php");
exit;
}
$stmtFileUpload->execute();
$_SESSION['thankyou'] = true;
header("Location: developerUpload_thankyou.php");
exit;
}catch(PDOException $e){
$errors[] = $file_name . 'not saved in db.';
echo $e->getMessage();
}
}
PHP Documentation bool move_uploaded_file ( string $filename , string $destination )
You did :
move_uploaded_file($file_tmp,$dir.'/'.$file_name)
move_uploaded_file is expecting $file_tmp to be a path to the tmp file but you used
$file_tmp = file_get_contents($_FILES['file']['tmp_name'][$key]);
so $file_tmp is no longer the path but the content it self
So to solve the upload problem just use the tmp file path instead.
if(!move_uploaded_file($_FILES['file']['tmp_name'][$key],$dir.'/'.$file_name)){
Also, you should remove addslashes() on the file name because it could create unexpected results. Instead, you can sanitize the filename using something like this:
$file_name = preg_replace("/[^a-z0-9\.]/", "_", strtolower($_FILES['file']['name'][$key]));
You should also consider adding a random number to the file name so users don't overwrite other users files that have the same name: me.png could be common for an avatar for example. Would be safer to save as
$filename = strtotime("now")."_me.png";
One last thing, using is_file() can also cause problems in certain cases
Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
use file_exists() instead
I am uploading files to a server using php and while the move_uploaded_file function returns no errors, the file is not in the destination folder. As you can see I am using the exact path from root, and the files being uploaded are lower than the max size.
$target = "/data/array1/users/ultimate/public_html/Uploads/2010/";
//Write the info to the bioHold xml file.
$xml = new DOMDocument();
$xml->load('bioHold.xml');
$xml->formatOutput = true;
$root = $xml->firstChild;
$player = $xml->createElement("player");
$image = $xml->createElement("image");
$image->setAttribute("loc", $target.basename($_FILES['image']['name']));
$player->appendChild($image);
$name = $xml->createElement("name", $_POST['name']);
$player->appendChild($name);
$number = $xml->createElement("number", $_POST['number']);
$player->appendChild($number);
$ghettoYear = $xml->createElement("ghettoYear", $_POST['ghetto']);
$player->appendChild($ghettoYear);
$schoolYear = $xml->createElement("schoolYear", $_POST['school']);
$player->appendChild($schoolYear);
$bio = $xml->createElement("bio", $_POST['bio']);
$player->appendChild($bio);
$root->appendChild($player);
$xml->save("bioHold.xml");
//Save the image to the server.
$target = $target.basename($_FILES['image']['name']);
if(is_uploaded_file($_FILES['image']['tmp_name']))
echo 'It is a file <br />';
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
else {
echo $_FILES['image']['error']."<br />";
echo $target;
}
Any help is appreciated.
Eric R.
Most like this is a permissions issue. I'm going to assume you don't have any kind of direct shell access to check this stuff directly, so here's how to do it from within the script:
Check if the $target directory exists:
$target = '/data/etc....';
if (!is_dir($target)) {
die("Directory $target is not a directory");
}
Check if it's writeable:
if (!is_writable($target)) {
die("Directory $target is not writeable");
}
Check if the full target filename exists/is writable - maybe it exists but can't be overwritten:
$target = $target . basename($_FILES['image']['name']);
if (!is_writeable($target)) {
die("File $target isn't writeable");
}
Beyond that:
if(!(move_uploaded_file($_FILES['image']['tmp_name'], $target))) {
echo $_FILES['image']['error']."<br />";
}
Echoing out the error parameter here is of no use, it refers purely to the upload process. If the file was uploaded correctly, but could not be moved, this will still only echo out a 0 (e.g. the UPLOAD_ERR_OK constant). The proper way of checking for errors goes something like this:
if ($_FILES['images']['error'] === UPLOAD_ERR_OK) {
// file was properly uploaded
if (!is_uploaded_File(...)) {
die("Something done goofed - not uploaded file");
}
if (!move_uploaded_file(...)) {
echo "Couldn't move file, possible diagnostic information:"
print_r(error_get_last());
die();
}
} else {
die("Upload failed with error {$_FILES['images']['error']}");
}
You need to make sure that whoever is hosting your pages has the settings configured to allow you to upload and move files. Most will disable these functions as it's a sercurity risk.
Just email them and ask whether they are enabled.
Hope this helps.
your calls to is_uploaded_file and move_uploaded_file vary. for is_uploaded_file you are checking the 'name' and for move_uploaded_file you are passing in 'tmp_name'. try changing your call to move_uploaded_file to use 'name'
I have the next code:
<?php
if(empty($_FILES))
echo 'vacia';
else
echo 'con algo';
var_dump($_FILES);
$tempFile = $_FILES['Filedata']['tmp_name'];
$fileName = $_FILES['Filedata']['name'];
move_uploaded_file($tempFile, "./" . $fileName);
?>
Now, empty($_FILES) is true because shows me the string 'vacia'. Also show me 'array(0) {}' in var_dump().
But move_uploaded_file() still works perfectly. Could someone explain me that?
the error_reporting(E_ALL) say 'Undefined index Filedata' in each line where I use it, but I can understand why move_uploaded_file() still works :/
You should check the return of move_uploaded_files():
$result = move_uploaded_files($tempFile, "./", $fileName);
It will be true on success or false on error. In your case, it should be false. Since the array indices do not exist, PHP will throw an E_NOTICE level error and use an empty string, so you're actually doing this:
move_uploaded_file('', "./", '');
But without E_NOTICE enabled, there will be no visible error message. (see http://php.net/manual/en/function.error-reporting.php)
You might want to check to see if the file exists instead. Just because the name exists doesn't mean the file exists.
if(is_file($_FILES['Filedata']['tmp_name'])){
echo 'vacia';
}else{
echo 'con algo';
exit("File doesn't exist, I can't move it so I'm out!");
}
var_dump($_FILES);
$tempFile = $_FILES['Filedata']['tmp_name'];
$fileName = $_FILES['Filedata']['name'];
move_uploaded_file($tempFile, "./" . $fileName);
I want to upload images to mysql server using php.
I have created html and sql connectivity but the image upload shows error.
I cant upload the image, it shows error of valid image i.e. you must upload jpeg,bmp,gif; and read/write in directory.
Can any1 help me solving this problem
the php file is
<?php
//Start session
session_start();
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
// Check to see if the type of file uploaded is a valid image type
function valid($file)
{
// This is an array that holds all the valid image MIME types
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif");
//echo $file['type'];
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
// Build our target path full string. This is where the file will be moved do
// i.e. images/picture.jpg
$TARGET_PATH = "image/";
$TARGET_PATH = $TARGET_PATH . basename( $_FILES['image']['name']);
$pimage = $_FILES['image']['name'];
// Check to make sure that our file is actually an image
// You check the file type instead of the extension because the extension can easily be faked
if (!valid($pimage))
{
$_SESSION['ERRMSG_ARR'] = array('You must upload a jpeg, gif, or bmp');
header("Location: admin.php");
exit;
}
// Here we check to see if a file with that name already exists
// You could get past filename problems by appending a timestamp to the filename and then continuing
if (file_exists($TARGET_PATH))
{
$_SESSION['ERRMSG_ARR'] = array('A file with that name already exists');
header("Location: admin.php");
exit;
}
// Lets attempt to move the file from its temporary directory to its new home
if (move_uploaded_file($_FILES['image']['tmp_name'], $TARGET_PATH))
{
// NOTE: This is where a lot of people make mistakes.
// We are *not* putting the image into the database; we are putting a reference to the file's location on the server
$sql = "insert into people (p_category, p_name, p_quantity, p_desc, p_image) values ('$pcategory', '$pname','$pquantity','pdesc', '" . $pimage['name'] . "')";
$result = mysql_query($sql);
//Check whether the query was successful or not
if($result) {
$_SESSION['ERRMSG_ARR'] = array('Product added');;
$_SESSION['MSG_FLAG'] = 0;
session_write_close();
header("location: admin.php");
exit();
}else {
die("Query failed: ".mysql_error());
}
}
else
{
// A common cause of file moving failures is because of bad permissions on the directory attempting to be written to
// Make sure you chmod the directory to be writeable
$_SESSION['ERRMSG_ARR'] = array('Could not upload file. Check read/write persmissions on the directory');
header("Location: admin.php");
exit;
}
?>
I think
$pimage = $_FILES['image']['name'];
should be
$pimage = $_FILES['image'];
You probably missed this because your code is quite inconsistent - sometimes you use $pimage, while elsewhere you reference the $_FILES array directly. This makes it harder to maintain should the file field's name change. You could also type hint the valid() function to make PHP complain if $file isn't an array:
function valid(array $file) { ... }
What level of error reporting do you have set? It would highlight errors like trying to access undefined array keys.
See you are passing the image type in the line if (!valid($pimage))
But in the valid() function you are again trying to get the type of image $file['type'].
What George said should also work, but since you are making variables for the image type $ptype and name $pimage, you can use them itself.
So the changes should be $file['type'] becomes $file and $file['type'] & in the insert query $pimage['name'] becomes $pimage
I'm sure this solves it, Bahua ;)