So I've been working on this thing for a few hours now and I'm worn out. When I try and update my contact information, and I choose a picture file it uploads the number 1, to my database, when I don't choose a picture I've succeeded in making the database keep the original picture file.
Can anybody help me figure this one out?
if (!empty($_FILES["kon_up_path"]["name"]))
{
$kon_up_path = move_uploaded_file($_FILES["kon_up_path"]["tmp_name"],"C:/xampp/htdocs/hansenservice/img/img/site/profil_pics/" . $_FILES["kon_up_path"]["name"]);
}
else
{
$kon_up_path = $kontakt_row['cont_img'];
}
Here's your problem:
$kon_up_path = move_uploaded_file(...);
move_uploaded_file() returns TRUE on success, and FALSE on failure. It does not return a path. If you want the path of the file, use the value you passed as the second argument of move_uploaded_file().
Bonus gotcha: you need to verify that the provided filename is acceptable. The code you've provided doesn't show you checking that it has an appropriate extension, doesn't contain any invalid characters, and doesn't already exist. If you're already doing this outside this snippet, great; if not, you need to, lest a user upload a file named ../../../../index.php (for instance) and blow away your site. Consider generating the filename automatically rather than letting the user specify it at all.
if(is_uploaded_file($_FILES['kon_up_path']['tmp_name'])) {
//code here
}
i think first print_r($_FILES) the error part contain non zero value so each time it will execute if this will happen then u have to
if($_FILES["kon_up_path"]["name"]['error'] == 0 ){
your code
}
$kon_up_path = move_uploaded_file($_FILES["kon_up_path"]["tmp_name"],"C:/xampp/htdocs/hansenservice/img/img/site/profil_pics/" . $_FILES["kon_up_path"]["name"]);
move_uploaded_file() this function return false / ture;
You can do like this:
if(move_uploaded_file($_FILES["kon_up_path"]["tmp_name"],"C:/xampp/htdocs/hansenservice/img/img/site/profil_pics/" . $_FILES["kon_up_path"]["name"])){
$kon_up_path = C:/xampp/htdocs/hansenservice/img/img/site/profil_pics/" . $_FILES["kon_up_path"]["name"];
}
try
if (count($_FILES) >= 1)
{
$kon_up_path = move_uploaded_file($_FILES["kon_up_path"]["tmp_name"],"C:/xampp/htdocs/hansenservice/img/img/site/profil_pics/" . $_FILES["kon_up_path"]["name"]);
}
else
{
$kon_up_path = $kontakt_row['cont_img'];
}
regards
Related
I've already asked a couple of questions regarding this and each step gets me closer however it still doesnt work as intended.
I want to upload an image and write it to the textfile, then when i upload another image that will be written to the end and so on so forth. So ultimately you'll have a long file with lots of images.
As far as i can tell my code should work but it doesn't. Here is a link to the site website for testing. Testing it maybe useful and below is the code.
It also always creates an empty element at the end of the array as you'll see from testing the site.
The PHP:
$sFileName = "imgDB.txt";
for ($i=0 ; $i < count($_FILES) ; $i++) {
move_uploaded_file(
$_FILES['file-'.$i]['tmp_name'],
"img/". $_FILES['file-'.$i]['name']
);
}
$sImgs = file_get_contents($sFileName); //gets a string from the file.
if (json_decode($sImgs, true) != false) {
$ajImgs = json_decode($sImgs, true);
} else {
$ajImgs = array();
}
$aOutPut = array_merge ($ajImgs, $_FILES);
$aSendToFile = json_encode(
$aOutPut,
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
);
file_put_contents($sFileName, $aSendToFile);
Some remarks
if the move_uploaded_file call is not protected further, this allows to upload any files, including script files - this opens a security vulnerability in your application - check for MIME-type and file-extension to avoid this
json_decode returns null if the input value is empty or cannot be decoded - not false like in your code
appending to an array is not done with array_merge, this just overrides the properties of $_FILES of the previous execution - use $aOutPut[] = $_FILES; instead
I have seen several websites where if you upload an image and an identical image already exists on there servers they will reject the submission. Using PNGs is there an easy way to check one image against a massive folder of images?
http://www.imagemagick.org/discourse-server/viewtopic.php?t=12618
I did find this with imagemagick, but I am looking for one vs many and not one to one a million
You can transform the file content into a sha1. That will give you a way to identify two pictures strictly identical.
see http://php.net/manual/fr/function.sha1-file.php
Then after you save it into a NFS, or use some kind of database to test if the hash already exists.
Details of the images are probably maintained in a database; while the images are stored in the filesystem. And that database probably has a hash column which is used to store an md5 hash of the image file itself, calculated when the image is first uploaded. When a new image is uploaded, it calculates the hash for that image, and then checks to see if any other image detail in the database has a matching hash. If not, it stores the newly uploaded image with that hash; otherwise it can respond with details of the previous upload. If the hash column is indexed in the table, then this check is pretty quick.
If I understood your question correctly. You want to find out if a specific image exists in a Directory with so many images, right? If so, take a look at the solution:
<?php
// CREATE A FUNCTION WHICH RETURNS AN ARRAY OF ALL IMAGES IN A SPECIFIC FOLDER
function getAllImagesInFolder($dir_full_path){
$returnable = array();
$files_in_dir = scandir($dir_full_path);
$reg_fx = '#(\.png|\.jpg|\.bmp|\.gif|\.jpeg)#';
foreach($files_in_dir as $key=>$val){
$temp_file_or_dir = $dir_full_path . DIRECTORY_SEPARATOR . $val;
if(is_file($temp_file_or_dir) && preg_match($reg_fx, $val) ){
$regx_dot_wateva = '/\.{2,4}$/';
$regx_dot = '/\./';
$regx_array = array($regx_dot_wateva, $regx_dot);
$replace_array = array("", "_");
$return_val = preg_replace($regx_array, $replace_array, $val);
$returnable[$return_val] = $temp_file_or_dir ;
}else if(is_dir($temp_file_or_dir) && !preg_match('/^\..*/', $val) ){
getFilesInFolder($temp_file_or_dir);
}
}
return $returnable;
}
// CREATE ANOTHER FUNCTION TO CHECK IF THE SPECIFIED IMAGE EXISTS IN THE GIVEN DIRECTORY.
// THE FIRST PARAMETER SHOULD BE THE RESULT OF CALLING THE PREVIOUS FUNCTION: getAllImagesInFolder(...)
// THE SECOND PARAMETER IS THE IMAGE YOU WANT TO SEARCH WHETHER IT EXISTS IN THE SAID FOLDER OR NOT
function imageExistsInFolder($arrImagesInFolder, $searchedImage){
if(!is_array($arrImagesInFolder) && count($arrImagesInFolder) < 1){
return false;
}
foreach($arrImagesInFolder as $strKey=>$imgPath){
if(stristr($imgPath, $searchedImage)){
return true;
}
}
return false;
}
// NOW GET ALL THE IMAGES IN A SPECIFIED FOLDER AND ASSIGN THE RESULTING ARRAY TO A VARIABLE: $imgFiles
$imgFolder = "/path/to/directory/where/there/are/images";
$arrImgFiles = getAllImagesInFolder($imgFolder);
$searchedImage = "sandwich.jpg"; //<== OR EVEN WITHOUT THE EXTENSION, JUST "sandwich"
// ASSUMING THE SPECIFIC IMAGE YOU WANT TO MATCH IS CALLED sandwich.jpg
// YOU CAN USE THE imageExistsInFolder(...) FUNCTION TO RETURN A BOOLEAN FLAG OF true OR false
// DEPENDING ON IF IT DOES OR NOT.
var_dump($arrImgFiles);
var_dump( imageExistsInFolder($arrImgFiles, $searchedImage) );
I have an array, which contains amongst other things a file path to a video file. There are various file formats .avi, .mp4 etc etc.
Now I only want to display the rows where the file path's file extension is .mp4.
Currently I'm using a function to extract the file extension, but I'm having trouble doing this on the fly while displaying the rows.
An example of the file path: c:\TempVideoDir\Office-P-cam01-20140826-083016.avi
The function im using to get the file ext:
function get_fileext($filename) {
$cut_fileext = (explode('.', $filename));
$just_fileext = $cut_fileext[1];
echo $just_fileext;
}
Which works fine.
Now I'm querying the database to get the filepath along with other details about the file, and I only want to display the rows where the file path contains a .mp4 file.
I've tried everything I could thing of/find on Google etc but this is what I currently have:
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row) {
if (in_array((get_fileext($row["Filename"])== "mp4"), $result)) {
echo " blah blah
I dont have the option of adding the file extension into the database table as this is backed up automatically by a piece of equipment.
So, whadoyareckon? is it possible to do it on the fly like this?
Any help is much appreciated!
Thanks
I dont think you can use in_array() like that. Its searching the entire index of the array, so when it looks ate $result[] its never going to find $row['filename'] with only an ext.
try this:
//looping through $result array
foreach($result as $row) {
//check if $row['filename'] has a string with a mp4 extension.
if (get_fileext($row["Filename"])== "mp4") {
echo "Row has a filename with the mp4 extension';
also as someone else pointed out fix your get_fileext() method to return something.
function get_fileext($filename) {
$cut_fileext = (explode('.', $filename));
$just_fileext = $cut_fileext[1];
return $just_fileext;
}
Your function isn't returning a value. It's emitting the value to the output:
function get_fileext($filename) {
$cut_fileext = (explode('.', $filename));
$just_fileext = $cut_fileext[1];
echo $just_fileext;
}
So there's no way for anything invoking that function to see that result. Instead, return the value:
function get_fileext($filename) {
$cut_fileext = (explode('.', $filename));
$just_fileext = $cut_fileext[1];
return $just_fileext;
}
That way the invocation of the function itself evaluates to the returned value, allowing you to use the function in your logic.
You could consider adjusting your database query to only return rows with ".mp4" files.
Change your query to have something like:
filepath = "%.mp4"
In MySQL the % operator is a wildcard, so this will match any strings ending in ".mp4"
so the title is not full clear, my question , I'm using the code to rename the file from directory present in the server the problem is i have to use the HTML form and php to update the file name, i want to do this : there will be an option on every file for renaming it when i click on the option the box pops up and i have to type the new name for file and save it , any help will be appreciated. (before down voting think about the question.)
The code that I'm using to update the file name
<?php
include("configuration.php");
$target = $_POST['filename'];
$newName = $_POST['newfilename'];
$actfoler = $_REQUEST['folder'];
$file = "files/users/";
$new ="files/users/";
$renameResult = rename($file, $new);
// Evaluate the value returned from the function if needed
if ($renameResult == true) {
echo $file . " is now named " . $new;
} else {
echo "Could not rename that file";
}
header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Try changing these lines:
$file = "uploads/$loggedInUser->username$actfolder/$target";
$new ="uploads/$loggedInUser->username$actfolder/$newName";
To:
$file = "uploads/{$loggedInUser->username}{$actfolder}/{$target}";
$new ="uploads/{$loggedInUser->username}{$actfolder}/{$newName}";
To explain why:
You are using variables inside a string, which means you will want to tell PHP where the variable ends. Especially when referencing objects or arrays, but also when you are placing variables right next to each other. I'm guessing PHP evaluated your original line to uploads/[Object]->usernamePizza/newname
I don't think you can call object properties in a string as you do.
try replace these lines :
$file = "uploads/".$loggedInUser->username."$actfolder/$target";
$new ="uploads/".$loggedInUser->username."$actfolder/$newName";
You may think about echoing $file and $new to confirm the path is nicely built.
On a side note, I'd recommend to really check the entries because this code can obviously lead to major security issues.
in php we can check if file exist using
if(file_exists("destination/"))
{
condition
}
but what I wanted to do is...
for example I already have this file on my destination
hello_this_is_filename(2).doc
how would I know if there is a file in that directory having a name containing a character
hello_this_is_filename
I wanted to search that way because... if there is exists on that directory, what will I do is... renaming the file into
hello_this_is_filename(3).doc
I also need to count the existence of my search so I know what number I'm going to put like
(3), (4), (5) and so on
any help?
Use glob.
if (count(glob("destination/hello_this_is_filename*.doc"))) {
//...
}
Leveraging Marc B's suggestion and xdazz, I would do something as follows:
<?php
$files = glob("destination/hello_this_is_filename*");
if (count($files)) {
sort($files);
// last one contains the name we need to get the number of
preg_match("([\d+])", end($files), $matches);
$value = 0;
if (count($matches)) {
// increment by one
$value = $matches[0];
}
$newfilename = "destination/hello_this_is_filename (" . ++$value . ").doc";
?>
Sorry this is untested, but thought it provides others with the regexp work to actually do the incrementing...