php random image file name - php

Okay im using a snippet I found on google to take a users uploaded image and put it in my directory under Content
But Im worried about duplicates so I was going have it upload the image as a Random number
well here is my code you can probably understand what im going for through it anyways
<label for="file">Profile Pic:</label> <input type="file" name="ProfilePic" id="ProfilePic" /><br />
<input type="submit" name="submit" value="Submit" />
$ProfilePicName = $_FILES["ProfilePic"]["name"];
$ProfilePicType = $_FILES["ProfilePic"]["type"];
$ProfilePicSize = $_FILES["ProfilePic"]["size"];
$ProfilePicTemp = $_FILES["ProfilePic"]["tmp_name"];
$ProfilePicError = $_FILES["ProfilePic"]["error"];
$RandomAccountNumber = mt_rand(1, 99999);
echo $RandomAccountNumber;
move_uploaded_file($ProfilePicTemp, "Content/".$RandomAccountNumber.$ProfilePicType);
And then basicly after all this Im going try to get it to put that random number in my database
Someone gave me a new snippet that looks like it will do what I want but now the file isnt making it all the way to my directory
$RandomAccountNumber = uniqid();
echo $RandomAccountNumber;
move_uploaded_file($ProfilePicName,"Content/".$RandomAccountNumber);

try using the php uniqid method to generate the unique id you need
http://php.net/manual/en/function.uniqid.php
$RandomAccountNumber = uniqid();
move_uploaded_file($ProfilePicTemp, "Content/" . $RandomAccountNumber);

When I upload images, I usually save it as the sha1() of the image's contents (sha1_file()). That way, you get two birds with one stone: You'll never (if you do, go fill out the closest lottery) get duplicate file names, AND, you'll prevent duplicate images (because duplicate images would have the same checksum).
Then, you have a database to sort out which image is which, and correctly display them to the user.

This is what I use when uploading pictures: a combination of session_id(), time() and a random string:
$rand = genRandomString();
$final_filename = $rand."_".session_id()."_".time();
function genRandomString()
{
$length = 5;
$characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWZYZ";
$real_string_length = strlen($characters) ;
$string="id";
for ($p = 0; $p < $length; $p++)
{
$string .= $characters[mt_rand(0, $real_string_length-1)];
}
return strtolower($string);
}
I hope this help.

random != unique
No matter what method you use to generate a 'random' file name you're probably going to want to do this to avoid collisions.
$path = '/path/to/directory/';
do {
$filename = some_function();
} while( file_exists($path.$filename) );
It's not super-necessary, but if you're just looking for peace of mind in case of a one-in-a-million filename collision then those couple extra lines will do the trick.

One of my favorite Coding Horror articles addresses why this approach is dumber than it looks, and you should use something like uniqid instead of mt_rand(1, 99999);...

Related

Updating Images Array

I have a table named tabel_foto which has 2 fields inside it, they are
foto (which contains the image's name), and
kondisi (which contains the image's description)
foto and kondisi's field value is from an-imploded multiple image upload. In other words, i have an upload form which it can upload multiple images, and those images are imploded before they are INSERTED into the sql table, like this :
I can show the image from my table as a list like this :
Please ignore it's bad layout, it's just a prototype/experiment before i add a new feature to my site
My question is, how to update those images to my table? I only want to update the image that is changed, i.e :
foto's field value is borobudur.jpg, bromo.jpg, merapi.jpg, prambanan.jpg, if i update the second image (bromo.jpg) from the form, i only want to update the "bromo.jpg" string in the foto field, how do i detect which image is changed on the form in php since the file upload button is a single file upload (not multiple upload) :
for($i = 0; $i < count($xplode_foto); $i++) {
?>
<img src="<?php echo $xplode_foto[$i]; ?>" id="<?php echo $i; ?>">
<input type="file" id="<?php echo $i; ?>" name="foto_kondisi" onChange="previewFotoJalan(this, this.id)">
<?php
}
Thanks in advance, i appreciate any solutions and answers :)
I would strongly suggest you to use a different mysql schema, like this.
photo_id
group_id
kondisi
Also, you can send a ajax request after every picture's upload , and refresh the page (or just a div).
This will make your life easier.. believe me... been there.
Success!!
Considering you save images on table column as img1,img2,img3 and description as desc1,desc2,desc3
and considering you use explode to update image.
you can make change like that:
<?php
$id = $_POST['imgid'];
//get images string from db and save to $x;
$images_array = explode(',', $x);
unset($images_array[$id]);
$y = implode (',', $images_array);
// now save again $y to db as images
//get description string from db and save to $x;
$desc_array = explode(',', $x);
unset($desc_array [$id]);
$y = implode (',', $desc_array);
// now save again $y to db as desc
Hope this help you

Form search save in file & display result

What is the most elegant and efficient way of search a string against injected script file in PHP.
The flow:
i want make form search when user input strings & click search, data searched save on txt/php file with auto create new file based on month & year ex: -201601.php / txt
then data was saved on safety query with serial key on each string
then if data on -201601.php contents have more than 1000+ query, the data old was deleted automatic
then how showing 50 strings based on random strings on -201601.php
then in -201601.php there are no double string or same string
If you have a solution for my issue and want to post an answer, please add some explanation so that I can understand why/how you did it so that I won't come asking the same questions all over again. Thanks
Im search & create file that i want making it with my plot imagination. Here is what I have so far manually :
<center>
<form action="./cari.php?q=" method="GET">
<input type="text" name="q" value="" placeholder=" Cari .." style="cursor: pointer;width:69%"/>
<input type="submit" value="Search"/>
</form>
</center><?php
if(isset($_GET['q'])) {
$data = ''.$_GET['q']."<br>\n";
$ret = file_put_contents('rcnt.php', htmlspecialchars($data), FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
//echo "$ret bytes written to file";
}
}
//else {die('no post data to process');}
?>
Im stuck searching with cant find related tutorial & hope find answer :(
Please your help, i want learn more with this, i use XAMPP 5.6
First step, the ?q= var the browser will create, you don`t need to set this on your form action.
<form method="get">
<input type="text" name="q" placeholder="search">
</form>
The PHP code will be:
<?php
if(!empty($_GET["q"]))
{
$file = fopen(date("Ym") . ".txt","a+");
fwrite($file, $_GET["q"] . "\r\n"); //\r\n jump the line
flose($file);
}
?>
If today is the 1st search of the 1st day of the month, the file will not exists, then, the PHP will create it, otherwise, will open and write on it.
Hope it could help you.
We could try this way:
<?php
$theFile = date("Ym") . ".txt";
$myFile = file($theFile);
for($i = 0; $i < 100; $i++){ //deleting the first 100 lines
unset($myFile[$i]);
}
//rewriting the file without the 100st first lines
file_put_contents($theFile, implode($myFile));
?>

Simple Captcha in PHP with rand()

I'm trying to make a simple captcha in PHP, but it does not work. The query is not currently executing. This is my current code:
<?php
$Random = rand(1, 100);
$Random2 = rand(1,100);
echo "Result: ".$Random." + ".$Random2." ?";
?>
<input type="text" name="r_input"/><br />
$Cap = mysql_real_escape_string($_POST['r_input']);
$Result = $Random+$Random2;
if(isset($_POST['myButton']) and trim($Var) and trim($Var2) and trim($Var3) and $Cap==$Result){
//My Query
}
When you use rand() to generate 2 values, and show those 2 values, and give the form for the user to enter the answer, ...
... the user enters the answer and submits back to the server ...
... the server gets the answer, and then GENERATES 2 NEW VALUES, that don't correspond to the answer given by the user.
Try using session variables to store the generated values in, and match against when the user submits the form!
<?php
session_start();
$captcha_id = 'captcha_' . rand();
$_SESSION['$captcha_id']['val1'] = rand(1,1000);
$_SESSION['$captcha_id']['val2'] = rand(1,1000);
echo "
<form action='' method='post'>
<p>Result: {$_SESSION['$captcha_id']['val1']} + {$_SESSION['$captcha_id']['val2']} = </p>
<input type='hidden' name='captcha_id' value='{$captcha_id}' />
<input type='text' name='captcha_answer' />
<p>?</p>
</form>
";
if (
isset($_POST['captcha_id'])
&& isset($_SESSION[$_POST['captcha_id']])
&& isset($_POST['captcha_answer'])
&& $_SESSION[$_POST['captcha_id']]['val1'] + $_SESSION[$_POST['captcha_id']]['val2'] == intval($_POST['captcha_answer'])
) {
unset($_SESSION[$_POST['captcha_id']]); // don't let this answer be reused anymore.
// do allowed stuff
}
?>
Because $Random and $Random2 have a different value each time.
When you show the form for the first time, they may have the values $Random = 12 and $Random2 = 26. The User sees those, adds them up correctly and types in 38 (which is the correct answer for those two values). The answer is sent to the script again, the values of $Random and $Random2 are generated again (this time as $Random = 23 and $Random2 = 30 which equals 53) and the answer the user has sent is not correct any more.
So you would need to store those values in hidden fields and add these up, instead of the generated ones, like so:
<input type="hidden" name="rand_1" value="<?php echo $Random; ?>">
<input type="hidden" name="rand_2" value="<?php echo $Random2; ?>">
<?php
if ($_POST['rand_1'] + $_POST['rand_2'] == $_POST['r_input']) {
// Query etc.
EDIT: As suggested by #nl-x you should use the Session variables instead of hidden fields to prevent abuse of the captcha:
<?php
$Random = $_SESSION['rand_1'] = rand(1, 100);
$Random2 = $_SESSION['rand_2'] = rand(1,100);
echo "Result: ".$Random." + ".$Random2." ?";
?>
And check those values against the given result afterwards:
<?php
$Cap = mysql_real_escape_string($_POST['r_input']);
$Result = $_SESSION['rand_1'] + $_SESSION['rand_2'];
if ($Result == $Cap) {
// ...
You never re-enter PHP mode after you output your form field:
<input type="text" name="r_input"/><br />
<?php // <----this is missing
$Cap = mysql_real_escape_string($_POST['r_input']);
Pardon me, but you are not making a real captcha. The purpose of the captcha is to distinguish the human from the bots. I would highly suggest you to pick a image database, and randomize a function to call a image. Internally, i would check if the text/description of the image matches with what the user typed.
The only thing you will rand() is what image to load from your image database.
That's a not-healthy way to do it, and there are plenty of better ways to do this. But it's more closer to a captcha than just your current code.
There is also a lot of libraries and engines that can do the job for you.
I'm not a pro at PHP, or even programming at all, but i think you're going to the wrong side - your code won't block any... malicious actions at all, or whatever kind of action that you will try to prevent with the captcha.
Search google for the libraries. PhpCaptcha is one of them. And here is a very simple quickstart guide for phpcaptcha.
Here's a code example, extracted from PHPCaptch that I linked above.
At the desired position in your form, add the following code to display the CAPTCHA image:
<img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
Next, add the following HTML code to create a text input box:
<input type="text" name="captcha_code" size="10" maxlength="6" />
[ Different Image ]
On the very first line of the form processor, add the following code:
<?php session_start(); ?>
The following php code should be integrated into the script that processes your form and should be placed where error checking is done. It is recommended to place it after any error checking and only attempt to validate the captha code if no other form errors occured. It should also be within tags.
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
This includes the file that contains the Securimage source code and creates a new Securimage object that is responsible for creating, managing and validating captcha codes.
Next we will check to see if the code typed by the user was entered correctly.
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}
Following the directions above should get Securimage working with minimal effort.
This code is included here as well.
Good luck!

Replace Space with Underscore so i can download a file.

I have a website that allows users to upload a file. when uploading the file on another page users can download that file. the problem is if the file name has a space in it will only pick up the first work not the whole file name. i was wondering is there a way to download the file with spaces in it or an easy option might be to add underscores to the file name so that it can be downloaded.
//This is the directory where images will be saved
$target = "../images/avatars/";
$target = $target . basename($_FILES['photoLocation']['name']);
// Check to see all fields have been completed
$photoLocation =($_FILES['photoLocation']['name']);
if (!empty($photoLocation))
{
// Create an SQL query to add the comment
$sql = "INSERT INTO tblPhotoUpload (photoLocation) VALUES ('$photoLocation')";
// Connect to the database
connect();
// Run the query and store the result in a variable
$result = mysql_query($sql) or die("Could not run query");
//Writes the photo to the server
if(move_uploaded_file($_FILES['photoLocation']['tmp_name'], $target))
// Close connection to the database
mysql_close()
And i am displaying the file like this.
while($record = mysql_fetch_array( $result ))
{
?>
<tr class="row">
<td class="cell"><a href= http://xxxxxxxxxxxxxxxxxxxxxx.com/images/avatars/<?php echo $record["photoLocation"];?>>Download</a> </td>
You're dealing with an escaping scheme within an escaping scheme when you work with URLs. In particular, you have to escape the URL so as to be a URL, and then you have to escape the URL as to embed it in HTML:
$url = "http://somesite.tld/some/path/" . urlencode($filename);
echo 'link';
It's pretty damn hard to think of a (realistic) situation that actually requires htmlspecialchars, but wooo paranoia!
Oh, and also, it's typically a good idea to just go ahead and quote all of your attribute values.
When you do: <tag attr=value with spaces> browsers interpret with and spaces as additional attributes, notas part of the value for attr
If you do go the replacement route though, you're just looking for a simple str_replace call:
$val = str_replace(' ', '_', $replaceMe);
Haven't tested but this logic seems right.
$name = str_replace(' ', '_', $photoLocation);
i would recommend to not display image by it original name, since there alot of security problems associated with that.
a way u can do it is to encode file name and save it in extra field in database.
example
$sql = "INSERT INTO tblPhotoUpload (photoLocation,photourl) VALUES ('$photoLocation','".md5($photoLocation)."')";
and when display use phtolocation in url and make display route that to photo location.
good luck,if u need full example let me know
str_replace()
$file= str_replace(' ','_',$file);
or in your case :
$target = $target . basename(str_replace(' ','_',$_FILES['photoLocation']['name']));
$photoLocation =(str_replace(' ','_',$_FILES['photoLocation']['name']));

Validating a cloned/repeatable input using PHP and/or jQuery

I'm trying to create a repeatable field (an upload image input with image preview) in PHP using jQuery.clone(). Everything works fine, except the return of the clone data.
In my PHP file, I have:
$i = 0;
$valid_input['image'] = $input['image'][$i];
then
return $valid_input;
used in an image upload input:
<input type="hidden" class="image" name="image[image]['.$i.']" value="'.$theme_options['image'].'" />
<input type="button" class="upload-button button" value="'. __( 'Upload Image', 'theme' ).'" />
the value of $i is set to 0 and counted with jQuery clone.
The problem is that the cloned fields disappear after submitting.
The original field "image['image'][0]" is saved and returns as valid, but the others (image['image'][1], [2], [3]...) don't validate!
If I change the value of $i like this:
$i = 1;
$valid_input['image'] = $input['image'][$i];
then the original input don't submit, only the clone, because the original is [0] and the clone is [1], but after submitting the clone returns as [0].
I tried things like:
$i = 0;
$valid_input['image'] = $input['image'][$i];
$i++; //-- I know, I'm stupid...this will not count the input!
Please, can somebody help me with this?
How can I be able to validate the cloned fields?
My Google searches are all marked as visited and I swear that I did not find anything that could solve this!
Any help would be greatly appreciated, thanks in advance!
Do you mean something like:
for($i = 0; $i < count( $input["image"] ); $i++) {
echo $input["image"][$i];
}
or did i get you wrong
please try with this
using the input name as image[] so you will get the value of image as an simple array by using the foreach you can do you validation.
i.e.,
$arrValue = $_POST['image'];
foreach ($arrValue as $key=>$value) {
//do the operations here
}

Categories