I already saw this question, but it didn't work for me.
What I need to do is to check whether a file exists, in PHP, without knowing the extension.
I use this code:
<?php
if (count(glob("/database/".$_REQUEST['thetitle'].".*")) == 0) {
echo 'true';
} else {
echo 'false';
}
?>
EDIT:
Maybe it's relevant saying that the script is located in
[root]/functions/validatefilename.php
and the database in
[root]/database/
But it always returns false, no matter what the filename ($_REQUEST['thetitle']) is.
try:
count(glob("./database/".$_REQUEST['thetitle'].".*"))
Looks to me like it works fine except that you should be specifying the full path:
if (count(glob( "/path/to/" . "database/" .$_REQUEST['thetitle']. ".*")) == 0) {
Related
Note: The file number is just so I can refer to each file easier
I am testing some code in which I have a file called first.txt (file 1) and and file called tom-first.php (file 2), file 2 file checks for the file 1's existence and sets a variable, then in my index.php(file 3), I require file 2 and if the variable is 1, I redirect to startup.php(file 4). File 4 deletes a text file called text.txt
My error is when I run the code, no matter what happens, test.txt is always deleted
tom-first.php
<?php
if (file_exists('first.txt')) {
$first = '1';
} else {
$first = '0';
}
echo $first;
?>
index.php
<?php
require 'tom-first.php';
if($first = '1')
{
header("Location: startup.php");
}
else
{
echo 'HI';
}
?>
Startup.php
<?php
unlink('text.txt')
?>
First.txt is Empty
I feel like the error is to do with setting variables on file 2 although echoing out $first shows the right number.
Any help is appreciated, even a completely different method of this would be useful, I am basically trying to make a system where it has a setup that runs on first time use.
You have a typo in index.php file.
Equality comparison operator in PHP is '==', not '='.
Your if statement below assigns value '1' to $first variable and always evaluates to '1'.
index.php
<?php
require 'tom-first.php';
if($first = '1') // this should be $first == '1'
{
header("Location: startup.php");
}
else
{
echo 'HI';
}
?>
With = you make an assignment (you assign a value to a variable). But == is a comparison operator. In your case you're evaluating 1 which is always TRUE. Another thing is, why so verbose and so many files if you can just write:
$first = file_exists('first.txt') ? 1 : 0;
and then the rest. Or even better...
if (file_exists('first.txt') {
unlink('first.txt');
// and do some other stuff
}
echo 'whatever';
But... :)
If you have to do something like this, it very much smells.
Why would you check for the presence of a file only to delete it right away?
Using a PHP script, I want to compare two images. One of the images is located on my server, and one is located on an external website. I have tried to compare the hashes of the two images to each other. Unfortunately, this only works when the two images are saved on my server. How can I make this work?
<?php
$localimage = sha1_file('image.jpg');
$imagelink = file_get_contents('http://www.google.com/image.jpg');
$ext_image = sha1_file($imagelink);
if($localimage == $ext_image){
//Do something
}
?>
If you are using php 5.1+ (which I hope) you can just write :
<?php
$localimage = sha1_file('image.jpg');
$ext_image = sha1_file('http://www.google.com/image.jpg');
if($localimage == $ext_image){
//Do something
}
?>
As sha1_file will work on remote wrappers.
Quote from PHP doc at https://secure.php.net/manual/en/function.sha1-file.php
5.1.0 Changed the function to use the streams API. It means that you can use it with wrappers, like sha1_file('http://example.com/..')
You are not using the sha1_file() properly in the second call.
sha1_file() expects the parameter to be a filename and you are using a memory buffer. So you have 2 options.
First using your current code, save the file to a temp location and use sha1_file()
<?php
$localimage = sha1_file('image.jpg');
$imagelink = file_get_contents('http://www.google.com/image.jpg');
file_put_contents('temp.jpg', $imagelink);
$ext_image = sha1_file('temp.jpg');
if($localimage == $ext_image){
//Do something
}
?>
Or use sha1() instead of sha1_file() on the contents of $imagelink
<?php
$localimage = sha1_file('image.jpg');
$imagelink = file_get_contents('http://www.google.com/image.jpg');
$ext_image = sha1($imagelink);
if($localimage == $ext_image){
//Do something
}
?>
Well actually maybe 3 options, see #Flunch's answer!
The code below needs to read the directory uploads/ but he always tells me that the directory is not empty, even when it totally is empty.
<?php
$dir = "uploads/";
echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
?>
Is there a error in this code or anything or am I just going crazy?
UPDATED CODE
<?php
echo (count(glob("uploads/*")) === 0) ? 'Empty' : 'Not empty';
?>
FULL PAGE CODE UPDATE
<?php
if (array_key_exists('error', $_GET)) {
echo '<div class="galleryError">That image could not be found, we're sorry!</div>';
} elseif (array_key_exists('unknownerror', $_GET)) {
echo '<div class="galleryError">There went something wrong</div>';
} else {
echo '';
}
if ($handle = opendir('uploads/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<div class='imgbox'><a href='fullscreen.php?token=$entry'><img src='$submap$gallery$entry' class='boximg'></a><p class='boxname'>$entry<br /><a href='?view&token=$entry'><small>View this image</small></a></p></div>";
}
}
closedir($handle);
}
// all the above is working but then we have this lonely code over here which refuses to work.
echo (count(glob("uploads/*")) == 0) ? 'Empty' : 'Not empty';
?>
glob is silently failing. I couldn't tell you why, with file system access it's usually permissions related but there could be other factors - it even says in the documentation that the functionality is partially dependent on your server environment...
On some systems it is impossible to distinguish between empty match and an error.
When there's a glob error it returns false - and count(false) === 1 (also documented) so it's no surprise folks get into confusing situations when they ignore these checks. If you really don't care about errors you can utilise the short-hand ternary operator to make an inline false-check, ensuring an array is always passed to count so it will behave as expected:
$isEmpty = count(glob("uploads/*")?:[]) === 0;
This still doesn't get around the fact that the directory is not being read though - have you tried printing the output of glob when you do have files in the directory? I'd imagine that's borked too. What does the following print? :
var_dump(is_readable('./uploads'));
Does the output of the following match your expected working directory? :
echo realpath('uploads');
FYI use var_dump when debugging, not print_r as suggested in the comments - it will give you more detail about the variables / types / structures / references etc. that you actually need.
In summary - things to consider:
What OS is running on the server? What mode is PHP running in? Is it running under SuPHP / FastCGI or similar context. What user owns the ./uploads directory, what permissions are set on it?
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
I would like to move a file from one directory to another. However, the trick is, I want to move file with entire path to it.
Say I have file at
/my/current/directory/file.jpg
and I would like to move it to
/newfolder/my/current/directory/file.jpg
So as you can see I want to retain the relative path so in the future I can move it back to /my/current/directory/ if I so require. One more thing is that /newfolder is empty - I can copy anything in there so there is no pre-made structure (another file may be copied to /newfolder/my/another/folder/anotherfile.gif. Ideally I would like to be able to create a method that will do the magic when I pass original path to file to it. Destination is always the same - /newfolder/...
You may try something like this if you're in an unix/linux environment :
$original_file = '/my/current/directory/file.jpg';
$new_file = "/newfolder{$original_file}";
// create new diretory stricture (note the "-p" option of mkdir)
$new_dir = dirname($new_file);
if (!is_dir($new_dir)) {
$command = 'mkdir -p ' . escapeshellarg($new_dir);
exec($command);
}
echo rename($original_file, $new_file) ? 'success' : 'failed';
you can simply use the following
<?php
$output = `mv "/my/current/directory/file.jpg" "/newfolder/my/current/directory/file.jpg"`;
if ($output == 0) {
echo "success";
} else {
echo "fail";
}
?>
please note I'm using backtick ` to execute instead of using function like exec