PHP - Rand Not Working
what am i doing wrong? I can't see it... I want to catch the rand variable but it doesn't. So I print an extra print at the bottom. So there should be two rand prints. Here's the code.
<html> <head><title></title> </head> <body> <form action='random.php' method='post'> <?php if(isset($_REQUEST['rand'])){ $rand = $_REQUEST['rand']; print $rand . "<br /><br />"; } else { print "rand: empty<br /><br />"; } $rand = rand(1,1000); print $rand."<br /><br />"; print "<input type='hidden' value='$rand' />"; ?> <input type='submit' value='scramble' /> </form> </body> </html>I forgot to tell ya that the if statement returns rand: empty. Help... Similar TutorialsHello everybody, I just have a quick question. I am trying to develop a webpage for dice rolling (to use for myself when i play dnd) Now, I know a lot of the random functions is computer languages are not truly random, and thus have some areas that the value will be the result more than others. What would be a good way to try to make it as "random" as possible, or am I just over-thinking it? Hey, This is my [faulty] PHP $input3 = array("BB, BB, BB, BB, BB, BB, BB, BB, BB, bb"); $rand_keys3 = array_rand($input3, 2); $BB1 = $input3[$rand_keys3[0]] . "\n"; $BB2 = $input3[$rand_keys3[1]] . "\n"; $input4 = array("HD, HD, HD, HD, HD, hd"); $rand_keys4 = array_rand($input4, 2); $HD1 = $input4[$rand_keys4[0]] . "\n"; $HD2 = $input4[$rand_keys4[1]] . "\n"; $input5 = array("DD, DD, DD, DD, DD, DD, DD, dd"); $rand_keys5 = array_rand($input5, 2); $D1 = $input5[$rand_keys5[0]] . "\n"; $D2 = $input5[$rand_keys5[1]] . "\n"; $input6 = array("CC, CC, CC, CC, CC, cc"); $rand_keys6 = array_rand($input6, 2); $C1 = $input6[$rand_keys6[0]] . "\n"; $C2 = $input6[$rand_keys6[1]] . "\n"; $input7 = array("HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, HG, hg"); $rand_keys7 = array_rand($input7, 2); $HG1 = $input7[$rand_keys7[0]] . "\n"; $HG2 = $input7[$rand_keys7[1]] . "\n"; And this is the error I'm getting: Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 48 Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 54 Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 60 Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 66 Warning: array_rand() [function.array-rand]: Second argument has to be between 1 and the number of elements in the array in /home/content/91/6351791/html/dogtrader.php on line 72 I've checked back over it all and looked up the function in various places to check what they say about it, but can't see which bit I'm going wrong wit! :[ If anybody has any advice as to what to do to fix it, it would be much appreciated. Cheers. Hi there, I have one question about the function rand(), What if i want to have an number between 0 and 360 Without 90 to 180 so 91,92,93,94.....180 can't be the number how can i do that? btw, I know its possible through if,while,for and so on. But is there an other way to do this? Hi,
I basically want a function that takes a parameter which is a percentage chance of the functioning returning true.
A user can move from tier 1->10 and at tier 1 there's a 70% chance to move to tier 2, from tier 2 there's a slightly less chance to move up, and so on.
I tried with the following piece of code:
public function rollTheDice($winnerPercentage) { $number = rand(1, 100); if ($number <= $winnerPercentage) return true; return false; }The above code makes logical sense to me: 1. Pick a random number between 1 and 100. 2. If that number is less than or equal to the percentage, then we passed (example, if the random number is less than or equal to 70.. there must be a 70% chance of this?) This however does not seem to work, in fact it appears that when simulating a roll, 70% fails at the very first step (where there is a 70% chance of winning..) To actually make it to tier 10, has yet to be accomplished, so by simulating this with unlimited attempts for 120 seconds straight doesn't seem to "win". I tried (just for fun) and change the if-statement so: if ($number >= $winnerPercentage) This seems to be working quite well, as the simulator quickly reaches tier 10 this way. Any suggestions to code changes, or can someone explain why it is working way better when exchanging less than with greater than? I have this in my code: $dr =rand(0, 100); echo $dr; Here are the last 5 refreshes: 997 6336 6144 1110 2914 similar results when I use mt_rand()... Really need a hand from someone mysql query is pretty basic. I have been ask to add a random order to this query. $query = "SELECT rd.user_id FROM {$regions_data_table} rd WHERE rd.field_id = {$regions_field_id} AND rd.value LIKE %s AND rd.user_id NOT IN (SELECT um.user_id FROM {$wpdb->base_prefix}usermeta um WHERE ((um.meta_key='wp_ul_disabled' AND um.meta_value=1) OR (um.meta_key='wp_ul_inactive' AND um.meta_value=1)) GROUP BY um.user_id)"; I have tried so many options but cannot seem to get it to work i am trying to insert order by rand(). Any help please? Hi,
I'm having a bit of trouble. I want to order the same 9 results by RAND(). Currently I have them ordered by 'avg' (average views) and that's working fine, but when I add a sub query to make those 9 results scatter by random it's causing some trouble.
Code I currently have that works:
$sql = "SELECT *, views / HOUR(TIMEDIFF(NOW(), date)) as avg FROM content WHERE date BETWEEN CURDATE() - INTERVAL 30 DAY AND NOW() - INTERVAL 2 HOUR AND views > 600 AND live = '0' ORDER BY avg DESC LIMIT 9"; Hey guys, I don't know what to do. I've got a script used for gamble: $gamble_rand = rand($number_of_tickets,$gamble_chance); if($gamble_chance == $gamble_rand){ If $number_of_tickets is set by 99 and $gamble_chance is set by 100 the chance is 1:100 that the If-Clause is not true. But it seems to me that PHP is making its on "random". Independent of the values PHP is interpreting that 20 times of 100 times the correct logic is false... If $number_of_tickets is set by 1 there's no big different. Its just a little bit less, but not the chance that it has to be. Thanks for helping and Merry Christmas :-) This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=326563.0 I have 2 sites here that does what i need them to do but i dont know how to put the 2 codes together i got it to upload all files and used rand() to give the files a # but it ends up giving them all the same # lol so they overwrite them selfs lol This site shows how to upload mltiple fiels with php. http://www.ehow.com/how_6345068_upload-multiple-files-php.html This site shows how to rename only 1 file uploaded with rand() http://php.about.com/od/advancedphp/ss/rename_upload.htm i pray this is not to hard to do and if any one gets bored after words can you show how to block a file type from being uploaded ? like php/exe types PS)i would call my self a php newbe lol and ty you for your time and help Code from http://php.about.com/od/advancedphp/ss/rename_upload.htm Code: [Select] <form enctype="multipart/form-data" action="upload.php" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> //This function separates the extension from the rest of the file name and returns it function findexts ($filename) { $filename = strtolower($filename) ; $exts = split("[/\\.]", $filename) ; $n = count($exts)-1; $exts = $exts[$n]; return $exts; } //This applies the function to our file $ext = findexts ($_FILES['uploaded']['name']) ; //This line assigns a random number to a variable. You could also use a timestamp here if you prefer. $ran = rand () ; //This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended. $ran2 = $ran."."; //This assigns the subdirectory you want to save into... make sure it exists! $target = "images/"; //This combines the directory, the random file name, and the extension $target = $target . $ran2.$ext; if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { echo "The file has been uploaded as ".$ran2.$ext; } else { echo "Sorry, there was a problem uploading your file."; } The code from http://www.ehow.com/how_6345068_upload-multiple-files-php.html Code: [Select] <form action="upload.php" method="post" enctype="multipart/form-data"> File: <input type="file" name="file[]"/><br/> File: <input type="file" name="file[]"/><br/> File: <input type="file" name="file[]"/><br/> <input type="submit" name="submit" value="Upload"/> </form> $destpath = "upload/" ; while(list($key,$value) = each($_FILES["file"]["name"])) { if(!empty($value)){ f ($_FILES["file"]["error"][$key] > 0) { echo "Error: " . $_FILES["file"]["error"][$key] . "<br/>" ; } else { $source = $_FILES["file"]["tmp_name"][$key] ; $filename = $_FILES["file"]["name"][$key] ; move_uploaded_file($source, $destpath . $filename) ; echo "Uploaded: " . $destpath . $filename . "<br/>" ; } } } I want to use the following code to upload images to my server (below code works great) Code: [Select] <?php $rand = rand(1,99999999999999); $member_id = $_SESSION['SESS_MEMBER_ID']; if(isset($_FILES['uploaded']['name'])) { $target = "gallery/"; $allowed_filetypes = array('.jpg','.gif','.bmp','.png'); $max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB) $fileName = basename($_FILES['uploaded']['name']); $target = $target . $fileName; $errors = array(); // Get the extension from the filename. $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Check if the filetype is allowed. if(in_array($ext,$allowed_filetypes)) { $errors[] = "The file you attempted to upload is not allowed."; } // Now check the filesize. if(filesize($_FILES['uploaded']['tmp_name']) > $max_filesize) { $errors[] = "The file you attempted to upload is too large."; } // Check if we can upload to the specified path. if(is_writable($target)) { $errors[] = "You cannot upload to the specified directory, please CHMOD it to 777."; } //Here we check that no validation errors have occured. if(count($errors)==0) { //Try to upload it. if(!move_uploaded_file($_FILES['uploaded']['tmp_name'], $target)) { $errors[] = "Sorry, there was a problem uploading your file."; } } //If no errors show confirmation message if(count($errors)==0) { echo "<div class='notification success png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> The file {$fileName} has been uploaded<br>\n </div> </div>"; //echo "The file {$fileName} has been uploaded"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } else { //show error message echo "<div class='notification attention png_bg'> <a href='#' class='close'><img src='img/cross_grey_small.png' title='Close this notification' alt='close' /></a> <div> Sorry your file was not uploaded due to the following errors:<br>\n </div> </div>"; //echo "Sorry your file was not uploaded due to the following errors:<br>\n"; echo "<ul>\n"; foreach($errors as $error) { echo "<li>{$error}</li>\n"; } echo "</ul>\n"; echo "<br>\n"; echo "<a href='gallery.php'>Go Back</a>\n"; } } else { //Show the form echo "Use the following form below to add a new image to your gallery;<br />\n"; echo "<form enctype='multipart/form-data' action='' method='POST'>\n"; echo "Please choose a file: <input name='uploaded' type='file' /><br />\n"; echo "<input type='submit' value='Upload' />\n"; echo "</form>\n"; //Echo Tests! echo "<br /><br />Random FileName: "; echo $rand; echo "<br />"; echo "member ID: #"; echo $member_id; } ?> i then want it to rename the files for example: "test.png" is uploaded and name changed to "92997863_321.png" (where first number is using my $rand then the "_" then second number is my $member_id) the script already got these pieces of information and also gets the file extension using the $ext code. can this be done, and can i also upload the new filename to my sql table? Okay, so I'm kind of a PHP noob.
But out of context, for this site that I'm designing, it's easiest if I make a directory in the temporary folder PHP uses. In my case, /tmp/ because I am on Linux.
I want to use rand() to generate a random name for the page. But I then realized something, rand() could produce duplicates. How do I prevent PHP from trying to make the same directory at the same time? I know there are functions that will check if a file exists but I'm assuming it'll fail if that directory is currently being created, right?
How do I assure thread safety?
I willing to change my idea and not use rand(). Is there a way to get a unique key for each anonymous user on my site?
http://paste.ee/p/OhiWv
The above is a link to a readable version of my code. The XMLHTTPREQUEST worked, and the array was pulled down. Was able to print out the undecoded/unparsed array. However, immediately afterwards, all code stops working.
<script> var xhr; if (window.XMLHttpRequest) { // Mozilla, Safari, ... xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE 8 and older xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("POST", "PHPLibrary/selectMemberResults.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(); xhr.onreadystatechange = display_data; var $phparray function display_data() { if (xhr.readyState == 4) { if (xhr.status == 200) { //alert(xhr.responseText); $phparray = xhr.responseText; document.getElementById("suggestion").innerHTML = $phparray; // // //......................................................? // The above line of code is the last thing to print or // to do anything that returns to the browser.... //.......................................................? // All lines below do nothing............................? // } else { //alert('There was a problem with the request.'); } } } document.write("Length of phparray Array :" + $phparray.length + "<"); var output = JSON.parse($phparray, function (key,val) { if ( typeof val === 'string' ) { // regular expression to remove extra white space if ( val.indexOf('\n') !== -1 ) { var re = /\s\s+/g; return val.replace(re, ' '); } else { return val; } } return val; } ); document.write("Length of Array :" + $output.length + "<"); for (var i=0; i < $output.length; i++) { document.getElementById("suggestion").innerHTML = $output[i].MEMBER_NAME; } </script> i dont understand what is wrong plz help me.
here is code
$name = "img/".rand(1,9999999).".png"; $myFile = $name; $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = $html; fwrite($fh, $stringData); fclose($fh); $file=$name; $fst=file_get_contents($file); $im=imagecreatefromstring($fst); imagefilter($im, IMG_FILTER_GRAYSCALE); imagefilter($im, IMG_FILTER_NEGATE); //Convert to Grey Scale for($i=0;$i<123;$i++){ for($j=0;$j<50;$j++){ $px=imagecolorat($im,$i,$j); if($px<0x303030){ imagesetpixel($im,$i,$j,0); }else{ imagesetpixel($im,$i,$j,0xffffff); } } } $database = unserialize(@file_get_contents("db.txt")); if($database === false) $database = array(); // modify the database if needed if($_SERVER['REQUEST_METHOD'] == 'POST'){ if($_POST['submit'] == 'Add') $database[$_POST['ident']] = substr($_POST['letter'], 0, 1); if($_POST['submit'] == 'Del') unset($database[$_POST['ident']]); if($fh = @fopen('db111.txt', 'w+')){ fwrite($fh, serialize($database)); fclose($fh); } }else{ $newimage = true; } $width = 130; $height = 40; $captcha_gridstart =1; $captcha_gridspace =2; $letters = findletters($im, $width, $height, $captcha_gridstart, $captcha_gridspace); $count = count($letters); $cellw = ($count > 0) ? intval(100 / $count) : 0; //dispeckle the image and GET co-ordinates of the characters of captcha image and return them. function findletters($image, $width, $height, $gridstart, $gridspace){ $offsets = array(); $o = 0; $atstartx = true; for($x = 0; $x < $width; $x++){ $blankx = true; for($y = 0; $y < $height; $y++){ if(imagecolorat($image, $x, $y) == 0){ $blankx = false; break; } } if(!$blankx && $atstartx){ $offsets[$o]['startx'] = $x; $atstartx = !$atstartx; }else if($blankx && !$atstartx){ $offsets[$o]['endx'] = $x; $atstartx = !$atstartx; $o++; } } $count = $o; for($o = 0; $o < $count; $o++){ for($y = 0; $y < $height; $y++){ $blanky = true; for($x = $offsets[$o]['startx']; $x < $offsets[$o]['endx']; $x++){ if(imagecolorat($image, $x, $y) == 0){ $blanky = false; break; } } if(!$blanky){ $offsets[$o]['starty'] = $y; break; } } for($y = $height-1; $y > $offsets[$o]['starty']; $y--){ $blanky = true; for($x = $offsets[$o]['startx']; $x < $offsets[$o]['endx']; $x++){ if(imagecolorat($image, $x, $y) == 0){ $blanky = false; break; } } if(!$blanky){ $offsets[$o]['endy'] = $y; break; } } } for($o = 0; $o < $count; $o++){ $offsets[$o]['ident'] = ""; for($x = $offsets[$o]['startx'] + $gridstart; $x < $offsets[$o]['endx']; $x += $gridspace){ for($y = $offsets[$o]['starty'] + $gridstart; $y < $offsets[$o]['endy']; $y += $gridspace){ $offsets[$o]['ident'] .= ((imagecolorat($image, $x, $y) == 0) ? "0" : "1"); #echo $offsets[$o]['ident'].'<br>'; } } } return $offsets; } $a=""; foreach($letters as $letter){ $asciiletter = $database[$letter['ident']]; if(!empty($asciiletter)) { $a.=$asciiletter; } } I need bit of help, so I am looking into a plugin created for newsletter where default is it shows ad but it has option to remove ads by checking the check box. Default is to send ads in newsletter but if you don't want to send ads through newsletter then check the box. The problem is, it seems like checkbox selected is not being picked up. Some help would be appreciated. The custom field in wp:
'label' => 'Hide newsletter ads', 'name' => 'hide_ads', 'type' => 'checkbox', 'instructions' => 'Checking the checkbox will remove ads', 'required' => 0, 'conditional_logic' => 0, 'wrapper' => array( 'width' => '', 'class' => '', 'id' => '', ), 'choices' => array( 'Hide newsletter ads' => 'Hide newsletter ads', ), 'allow_custom' => 0, 'default_value' => array( ), 'layout' => 'block', 'toggle' => 0, 'return_format' => 'value', 'save_custom' => 0, ),
This is the php code for it: <!doctype html> <html lang="en-GB"> <head> <meta name="viewport" content="width=device-width" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="x-apple-disable-message-reformatting"> <title><?php the_title(); ?></title> <style> <?php require ABSPATH . 'path/newsletter.css'; ?> </style> <!--[if mso]> <style type="text/css"> .outlook-fallback-font { font-family: 'Lucida Bright', 'Cambria', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; } </style> <![endif]--> </head> <?php $hide_newsletter_ads = get_field('hide_ads'); echo $hide_newsletter_ads; ?> <body itemscope itemtype="http://schema.org/EmailMessage"> <div class="wrap"> <?php if (!$hide_newsletter_ads) { include ABSPATH . 'path/ad-banner.php'; } ?> <div class="header"> <a href="<?php bloginfo( 'url' ); ?>"> <img src="<?php echo get_home_url().'logo.png' ?>" alt="News" /> </a> </div> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php if ( get_field( 'newsletter_summary' ) ) { ?> <div class="newsletter-summary"><?php the_field( 'newsletter_summary' ); ?></div> <?php } ?> <?php if ( have_rows( 'newsletter_content' ) ) : ?> <?php // Loop through the ACF blocks $count = 0; while ( have_rows( 'newsletter_content' ) ) : the_row(); if ( get_row_layout() === 'story' ) : ?> <?php if ( 0 === $count ) { ?> <span class="date outlook-fallback-font"><?php the_time( 'd M Y' ); ?></span> <?php } ?> <?php if ( get_sub_field( 'story_heading' ) ) : ?> <h1><?php the_sub_field( 'story_heading' ); ?></h1> <?php endif; ?> <div class="content"> <?php the_sub_field( 'story_content' ); ?> </div> <?php endif; if ( 'post_list' === get_row_layout() ) : ?> <?php $posts = get_sub_field( 'post_list' ); if ( $posts ) : ?> </div> <div class="story-list"> <h2><span class="wrap"><?php the_sub_field( 'post_list_heading' ); ?></span></h2> <div class="wrap-table"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <?php // Output story cards foreach ( $posts as $i => $post ) { if ( 0 === $i % 2 ) { echo '<tr>'; } $class = ( 0 === $i % 2 ) ? 'odd' : 'even'; $image_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( 640, 345 ) ); $image_srcset = wp_get_attachment_image_srcset( get_post_thumbnail_id( $post->ID ) ); echo sprintf( '<td class="story-cell %4$s" valign="top"> <a href="%1$s" class="story-card outlook-fallback-font"> <img src="%3$s" alt="" height="120" style="height: 150px; object-fit: cover;" /> <span>%2$s</span> </a> </td>', esc_url( get_permalink( $post->ID ) . '?utm_source=newsletter&utm_medium=email&utm_campaign=newsletter' ), // permalink esc_html( get_the_title( $post->ID ) ), // title // esc_attr( $image_src[0] ), // image - src esc_attr( $image_src[0] ), // image - src esc_attr( $class ) // class ); if ( 0 !== $i % 2 || count( $posts ) === ( $i + 1 ) ) { echo '</tr>'; } } ?> </table> </div> </div> <div class="wrap"> <?php endif; endif; if (!$hide_newsletter_ads) { (0 === $count) { include ABSPATH . 'path/mpu-1.php'; } if (1 === $count) { include ABSPATH . 'path/mpu-2.php'; } } $count++; endwhile; endif; ?> <div class="footer"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td align="left"> © <?php echo esc_html( date( 'Y' ) ); ?> </td> <td class="footer-link"> <a href="<?php echo get_permalink( get_page_by_path( 'privacy-policy' ) ); ?>">Privacy Policy</a> · <a href="%unsubscribe_url%">Unsubscribe</a> </td> </tr> </table> </div> </div> <?php endwhile; endif; ?>
When I echo the POST, it echoes the correct value. The MySQL portion seems to just ignore it all together. I've tried changing the dropdown option to just a text field, same thing occurred. I have text fields right above this particular one that update just fine with the SAME exactly scripting. if POST, update query, done. Works. This one for some reason will not. MySQL portion: if ($_POST['bUpdate']){ mysql_query("UPDATE `Patients` SET `b` = '$_POST[bUpdate]' WHERE `id` = '".$_GET['id']."'"); } echo $_POST['bUpdate']; Form Portion: Code: [Select] <tr onmouseover="color(this, '#baecff');" onmouseout="uncolor(this);"> <td width="310" colspan="2" align="center"><span class="fontoptions">Postcard Status </span><br /> <? if ($data['b'] == 1){ echo '<select name="bUpdate"><option value="1" selected>Yes</option><option value="0">No</option></select>'; } else { echo '<select name="bUpdate"><option value="1">Yes</option><option value="0" selected>No</option></select>'; } ?> </td> </tr> I'm trying to turn this while loop into a for loop and am unable to get my result set to display properly in the for loop. The while works fine I just want to be able to have more control over which information is shown in my table as I loop and was wanting to use a for loop that way I can take advantage of the counter variable while i"m displaying my information. Any help would be appreciated. while ($row = mysql_fetch_assoc($data_result_set)) { echo "<td>".$row["product_id"]."</td>"; echo "<td>".$row["city"]."</td>"; echo "<td>".$row["quantity"]."</td>"; } *** I'm wanting it to look like something like this but can't figure out how to properly work in which row to display with the $i variable. $count=mysql_num_rows($data_result_set); for($i = 0; $i <= $count; $i++){ echo "<td>".mysql_fetch_assoc[$i]["product_id"]."</td>"; echo "<td>".mysql_fetch_assoc[$i]["city"]."</td>"; echo "<td>".mysql_fetch_assoc[$i]["quantity"]."</td>"; } I know the syntax for the for loop is totally off with the method mysql_fetch_assoc just dropped in there like a jerk but I'm just kinda pseudoing it out. Any help would be appreciated. Thanks in advance. Hi, I have the following file structure /.htaccess /index.php /displaypage.php All files are on root. I have following written in .htaccess file Options FollowSymLinks RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-z0-9-]+)$ displaypage.php?page=$1 [NC,L] I have following written in displaypage.php echo $_GET["page"]; Now when I run http://localhost/ then it shows index.php page which is correct. If I run http://localhost/something then it shows a blank page. Previously it used to display that "page" variable on screen. mod_rewrite is enabled and I am using Windows with XAMPP. What am I doing wrong? Thanks I just did a huge import from an app I have been working on. No issues except for this. I uploaded & imported all files & databases from my wampserver (localhost, local server) to my main online server. Before I continue with the problem, I have to give you info on how the files work. I am using a "controller" to view the files. Meaning, from index.php, I call all the files. For example, instead of mysite.com/register.php, its mysite.com/index.php?page=register. The index defines the doctype & html tags etc. The other files that are called through index.php are just pure php code, it does not contain the head & body tags etc. So, the issue is , when the surfer submits a form, i need to set a cookie. this cookie is VERY important. I cannot get it to work. I am getting the header warnings after submit Of course, this is to be expected. But I tried it on my local server, & it worked. I am not very familiar with cookies, this is a side of PHP i never really even touched. I know almost everything but that. So the php code is before the html code on the page, so I figured it was worth a shot. Im guessing the problem here is, since the code being outputted as index.php code + the form page code. So the cookie is being set after the html tags. How can I fix this? I need it to work thru the controller. I cannot just make it a single file, all files on the site needs to be thru this controller, otherwise it will mess everything up. Ino I could just add the code from index.php plus the form page code & just run the php code before all of the html tags, but like I said it has to be called thru index.php. I appreciate your replies, & I hope you guys dont think im an idiot & can understand my question, im terrible with words! Alrighty, I have been working on a simple hit counter and I can't quite get it to work, I am having trouble getting the system to actually display the amount of hits, here is the code for review. This code below is located within the file I call 'count_processor.php' <?php $myfile = "counter/hits.txt"; if(file_exists($myfile)) //Check for file { $var = fopen('$myfile,\'r+\''); //opens in read and write mode our file $visits = fread($var,filesize($myfile)); //puts the content of the file for its whole lenght rewind( $var ); //resets the file position indicator to the beginning $visits++; //increments the actual number of vists by 1 fwrite($var, $visits); //writes in the variable the actual (incremented) value fclose($var);//closes our file reference } else { print "File $myfile doesn't exist..."; Die(); //if the file doesn't exist prompts a warning and kills the script } $message = sprintf("%s recent visitors",$visits); //saves our visits message in a variable ($message) that will be used as output print $message; ?> Now, this small snippet of code is located on the page I want to count hits for, which is the index.php file. This calls upon the above code and in turn renders the data onto the page, but all that is showing up on the index.php page is 'recent visitors' which is the text after the numerical value of visitors is displayed, i.e. "137 recent visitors" <?php include 'counter/count_processor.php'; ?> Any ideas? Thanks! Also, you will notice I am using a flat-file system (.txt), no MySQL database. |