PHP - Put Csv File Contents Into Text Area And Choose Random Line
Similar TutorialsThis is a section of my code that goes and gets videos from any video site. What I’m having issues with is having it post a random title, that are all in a text file called titles.txt. What I’m wanting to accomplish is have my script go pull the video embed code, the duration, the tags, etc. Which all works fine until I get to the title part where it pulls locally from the server from the text file. I'm not an advance programmer so not sure if I am even approaching this correct way. Here is the code I have that is responsible for putting the title in. I appreciate your help. $video = array( ‘user_id’ => $this->user_id, ‘status’ => $this->status, ‘site’ => ‘my site’, ‘id’ => ‘’, ‘embeddable’ => true, ‘url’ => ‘’, ‘titles’ => ‘’, ‘title’ => ‘’, ‘description’ => ‘’, ‘tags’ => ‘’, ‘category’ => ‘’, ‘thumbs’ => array(), ‘duration’ => 0, ‘embed’ => ‘’ ); function random_title () { $titles = file (“titles.txt”, FILE_IGNORE_NEW_LINES); $num = rand (0, intval (count ($titles) / 3)) * 3; return ucwords($titles[$num]); } //Title if(preg_match(’/title="(.*?)"/’, $match, $matches_title)) { $video[‘title’] = random_title(). ’ - My site name’; } else { $this->errors[] = ‘Failed to get video title for ‘.$video[‘url’].’!’; if (!$this->debug) continue; else $debug_e[] = ‘TITLE’; }
Hi, Im trying to make a script to mass update a load of links in my database but im stuck on the basics, How can i detect a new line in a text area? Anyone know why this dosen't work? Code: [Select] <?php if($_POST[newlinks]) { $newlinks = preg_split("\n", ($_POST['newlinks'])); $i = 1; foreach ($newlinks as $newlink) { echo "$i - $newlink <br />"; $i++; } } else { echo "<form method=\"POST\" action=\"changehost.php\">"; echo "<br /> <strong>Enter the new links to try and replace old ones</strong> <br />"; echo "<textarea rows=\"16\" name=\"newlinks\" cols=\"84\"></textarea>"; echo "<input type=\"submit\" value=\"Submit\" name=\"B1\">"; ?> I am having problems with these slashes. They keep showing up when I echo data.... The code is to update a field in a mysql database table. Here is my code: Code: [Select] $query = mysql_query("SELECT * FROM `bus` WHERE username='$username'"); $row = mysql_fetch_array($query); $bio = $row['about']; $bio = str_replace("<br />","\r\n",$bio); if(isset($_POST['submit'])){ if(empty($errors)){ if($password == $pass){ $about1 = mysql_real_escape_string($_POST["about"]); $about1 = str_replace("\r\n","<br />",$about1); mysql_query("UPDATE bus SET about='$about1' WHERE username='$username'"); }else{$errors[] = 'Incorrect Password';} } } When I run this and put: About: I'm very tired today It's been very hard I get the about1 string as: I\\\'m very tired today\r\nIt\\\'s been very hard Why??? I need to choose a random number that doesn't currently exist in the database So, I'm trying to get this read my text document "news.txt" and display the contents. My code: Code: [Select] div.newscontent{ padding:0px; margin-top:60px; margin-bottom:0px; margin-left:400px; margin-right:0px; position:absolute; width:457px; height:330px; text-align:center; color:#FFFFFF; } Code: [Select] <div class='newscontent'> <?PHP $filename = "news.txt"; $arr = file($filename); foreach($arr as $line){ print $line . "<br/>"; } ?> </div> This is the output I get: Code: [Select] "; } ?> Whats wrong? I have a Php application that already has 2 buttons with input on the index page that perform some functions and output to different Php pages. Works good. How do I add a button with no input that would just perform a function and then just display a popup window showing the contents of a text file? I want to add several of these buttons for different functions and just display the contents of the resulting text files in popup windows. Any help would be greatly appreciated. Thanks in advance. Hi guys, I have script which scraps content from web and writes it down in a text file, now everything seems to be okay. Its scraps and writes well but the problem is when i open that text file one weird character keeps coming after some words which i don't know about. I have attached the text file, will you guys please look at it and tell me how to replace that square looking character into new line in text file. Hi, Have a text file that is being read. I want to print the contents however I want each line of the text file to appear on a new line in the browser. So far $str = file_get_contents('records.txt'); $lines = explode("\n", $str); echo $lines[0]; Help appreciated I'm ok with PHP but probably not half as good as some of you guys on here. I am basically trying to find a way to grab a line from a huge and I mean huge text file.... its basically a list of keywords I want to call by line number but without preferably going through them all before I get to that line.....otherwise couldmcrash my server obviously. At the moment im using this Code: [Select] $lines = file('http://www.mysite.com/keywords.txt'); // Loop through our array, show HTML source as HTML source; and line numbers too. foreach ($lines as $line_num => $line) { echo "$line_num"; } This works but im sure theres gotta be a better way of doing to save on usuage because this is putting the whole file into the memory and if I can simply say to php give me line number 97, would umm RULE.... Hope you guys can come up with a solution as your much smarter than me ty The title says it all,..well as all u can see, there are many methods to accomplish this done but not before undergoing through a heavy tasking process. For instance, 1. Open the file 2. Reads the content of the file into array. 3. Find out the desire line of text that we want to replace. 4. Make that line of text as variable and assigns with the new data(that we want to replace) as its values. 5.open another file. 6.Write the whole contents to the file opened in 5. 7. Put the contents back to the file of original. Can anyone contributes a better way to get this done? Like replace/delete a specific line without affecting other characters or anything therein? Thanx. P.S reading and using str_replace to make the alteration always ends up in giving some kind of result beyond desired after the first round of code execution. Here's what I'm trying to do, and I am having trouble getting started with this. It's a very simple process, but I didn't want to spend the next 6 hours in frustration, so some help getting started would be great. Here's the purpose of the script: 1. Allow user to add a text file to a form. 2. Take the text file, add HTML code to the beginning and end of each paragraph (a single line of text, usually paragraphs would be separated by a line return) 3. Send the user an email with the HTML file attached and thank them or whatever. 4. Allow the system to throttle itself (one-at-a-time) so that many people using the site won't bog it down. These files will probably be anywhere from 100 KB to 1,000 KB in size, usually hitting in the 300-500KB range. Here's what I can do very easily: 1. Allow user to add a text file - very simple and straightforward. 2. Take the text file, add HTML... - this is what I need a little help figuring out. Each paragraph needs to have <p> at the beginning and </p> at the end, and the script will also search for keywords on certain lines (section headers) and add a <align="center"> tag to that, and so forth. I can handle the formatting rules, but making sure the loop runs correctly could be a problem. 3. Send the user an email... - very easy, I can do that myself. 4. Allow the system to throttle itself... - this could be tricky. I was thinking a database with a TINYINT field, 0 for not processed yet, 1 for processing, 2 for processed. Cron job checks the next one on the list to see if it needs to send it to the processor, if the file is already being processed, or can be sent to a different database (completed entries) and removed from the current queue. The cron job would also be responsible for triggering the "Your file is converted!" email and the attachment. Any/all help would be greatly appreciated on this. I am going to work on the parts that I can do myself, and I'll be checking back for the discussion - in between Mountain Dew runs. I have a PHP file that is executed via batch file very frequently for live updating. This is a sort of "sync" file for reading/writing to a MySQL database. I am able to get it functioning absolutely fine when executed manually via a web browser (and my echo debug lines output the expected information), yet when I run the same PHP file via the command line, it seems to just not be capable of opening any file for reading, so the equivalent variables that are correct when executed on a web browser are blank when echoed through the command line. Is there a different way of handling reading of files when running a php script via the command line, or should it function exactly the same as when run via a browser? For instance: $k = "0"; $line = file("examplefile.log")[$k]; echo $line; I'm trying to work out if in my form my image field, which currently asks the user to upload from their hard drive, can show the contents of a server folder to select an image or upload a new one. Can this be done?? I have some code where i input data and upload images to a database (working 100% correctly) However I want to expand on it - what I want is when a user uploads an image of their choice, to assign it to a directory of their choosing. Then, when input is successful, write the directory of where the image is stored (not just the image) to the database. Here is the code; Code: [Select] <?php ini_set('display_errors',1); error_reporting(-1); require_once ('./includes/config.inc.php'); require_once (MYSQL); $add_cat_errors = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Check for a name: if (empty($_POST['product'])) { $add_cat_errors['product'] = 'Please enter the name!'; } // Check for a description: if (empty($_POST['prod_descr'])) { $add_cat_errors['prod_descr'] = 'Please enter the description!'; } // Check for a category: if (!isset($_POST['cat']) || !filter_var($_POST['cat'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_product_errors['cat'] = 'Please select a category!'; } // Check for a price: if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) { $add_cat_errors['price'] = 'Please enter a valid price!'; } // Check for an image: if (is_uploaded_file ($_FILES['image']['tmp_name']) && ($_FILES['image']['error'] == UPLOAD_ERR_OK)) { $file = $_FILES['image']; $size = ROUND($file['size']/1024); // Validate the file size: if ($size > 512) { $add_cat_errors['image'] = 'The uploaded file was too large.'; } // Validate the file type: $allowed_mime = array ('image/jpeg', 'image/JPG', 'image/jpg'); $allowed_extensions = array ('.jpg', 'jpeg'); $image_info = getimagesize($file['tmp_name']); $ext = substr($file['name'], -4); if ( (!in_array($file['type'], $allowed_mime)) || (!in_array($image_info['mime'], $allowed_mime) ) || (!in_array($ext, $allowed_extensions) ) ) { $add_cat_errors['image'] = 'The uploaded file was not of the proper type.'; } // Move the file over, if no problems: if (!array_key_exists('image', $add_cat_errors)) { // Create a new name for the file: $new_name = (string) sha1($file['name'] . uniqid('',true)); // Add the extension: $new_name .= ((substr($ext, 0, 1) != '.') ? ".{$ext}" : $ext); // Move the file to its proper folder but add _tmp, just in case: $dest = "../db/images/$new_name"; if (move_uploaded_file($file['tmp_name'], $dest)) { // Store the data in the session for later use: $_SESSION['image']['new_name'] = $new_name; $_SESSION['image']['file_name'] = $file['name']; // Print a message: echo '<h4>The file has been uploaded!</h4>'; } else { trigger_error('The file could not be moved.'); unlink ($file['tmp_name']); } } // End of array_key_exists() IF. } elseif (!isset($_SESSION['image'])) { // No current or previous uploaded file. switch ($_FILES['image']['error']) { case 1: case 2: $add_cat_errors['image'] = 'The uploaded file was too large.'; break; case 3: $add_cat_errors['image'] = 'The file was only partially uploaded.'; break; case 6: case 7: case 8: $add_cat_errors['image'] = 'The file could not be uploaded due to a system error.'; break; case 4: default: $add_cat_errors['image'] = 'No file was uploaded.'; break; } // End of SWITCH. } // End of $_FILES IF-ELSEIF-ELSE. // Check for a stock: if (empty($_POST['stock']) || !filter_var($_POST['stock'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['stock'] = 'Please enter the quantity in stock!'; } if (empty($add_cat_errors)) { $query = "INSERT INTO product (product, prod_descr, catID, price, image, stock) VALUES (?, ?, ?, ?, ?, ?)"; // Prepare the statement: $stmt = mysqli_prepare($dbc, $query); // For debugging purposes: // if (!$stmt) echo mysqli_stmt_error($stmt); // Bind the variables: mysqli_stmt_bind_param($stmt, 'sssssi', $name, $desc, $_POST['cat'], $_POST['price'], $_SESSION['image']['new_name'], $_POST['stock']); // Make the extra variable associations: $name = strip_tags($_POST['product']); $desc = strip_tags($_POST['prod_descr']); // Execute the query: mysqli_stmt_execute($stmt); if (mysqli_stmt_affected_rows($stmt) == 1) { // If it ran OK. // Print a message: echo '<h4>The product has been added!</h4>'; // Clear $_POST: $_POST = array(); // Clear $_FILES: $_FILES = array(); // Clear $file and $_SESSION['image']: unset($file, $_SESSION['image']); } else { // If it did not run OK. trigger_error('The product could not be added due to a system error. We apologize for any inconvenience.'); unlink ($dest); } } // End of $errors IF. } else { // Clear out the session on a GET request: unset($_SESSION['image']); } // End of the submission IF. require_once ('./includes/form_functions.inc.php'); ?> <form enctype="multipart/form-data" action="add_product.php" method="post" accept-charset="utf-8"> <input type="hidden" name="MAX_FILE_SIZE" value="524288" /> Product<br /><?php create_form_input('product', 'text', $add_cat_errors); ?> Description<br /><?php create_form_input('prod_descr', 'textarea', $add_cat_errors); ?> Category<br /><select name="cat"<?php if (array_key_exists('cat', $add_cat_errors)); ?>> <option>Select One</option> <?php // Retrieve all the categories and add to the pull-down menu: $q = 'SELECT catID, cat FROM category ORDER BY cat ASC'; $r = mysqli_query ($dbc, $q); while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; // Check for stickyness: if (isset($_POST['cat']) && ($_POST['cat'] == $row[0]) ) echo ' selected="selected"'; echo ">$row[1]</option>\n"; } ?> </select><?php if (array_key_exists('cat', $add_cat_errors)) echo $add_product_errors['cat']; ?> Price<br /><?php create_form_input('price', 'text', $add_cat_errors); ?> Image<br /><?php // Check for an error: if (array_key_exists('image', $add_cat_errors)) { echo $add_cat_errors['image'] . '<br /><input type="file" name="image"/>'; } else { // No error. echo '<input type="file" name="image" />'; // If the file exists (from a previous form submission but there were other errors), // store the file info in a session and note its existence: if (isset($_SESSION['image'])) { echo "<br />Currently '{$_SESSION['image']['file_name']}'"; } } // end of errors IF-ELSE. ?> <br /> <select name="select"> <option value="full_heads">db/images/full_heads</option> <option value="human_hair">db/images/human_hair</option> </select> Stock<br /><?php create_form_input('stock', 'text', $add_cat_errors); ?> <input type="submit" value="Add This Product" class="button" /> </fieldset> </form> How do I achieve this? Hello Everyone, I am a noob at PHP so please forgive me if my code is wrong. I have a strong understanding of HTML and CSS just for the curious. Question: Write a program that formats a block of text (to be input by the user) based on preferences chosen by the user. Give your user options for color of text, font choice and size. Display output on a new page. I would greatly appreciate someone's help. The text is showing up but not according to the options selected. I know there is something wrong with the output page. Here is the Input Page (call it question4.php): <html> <head> <title> Please Enter Your Text</title> </head> <body> <form method="post" action="question4display.php"> <p>Enter the text you want formatted please: <input type="text" name="textformat" maxlength="30" size="30" /> <table> <tr> <td><label for="font">Select Font:</label></td> <td><select id="font" name="font"> <option value="Verdana">Verdana</option> <option value="Arial">Arial</option> <option value="Times New Roman">Times New Roman</option> </select> </td> </tr> <tr> <td><label for ="size">Select Size:</label></td> <td><select id="size" name="size"> <option value="10px">10px</option> <option value="12px">12px</option> <option value="14px">14px</option> <option value="20px">20px</option> </select> </td> </tr> <tr> <td><label for="color">Select Color:</label></td> <td><select id="color" name="color"> <option value="green">Green</option> <option value="blue">Blue</option> <option value="red">Red</option> </select> </td> </tr> </table> <input type="submit" name="submit" value="Submit" /> </form> </body> </html> Here is the OUTPUT page (called it:question4display.php): <?php session_start(); $_SESSION['textformat'] = $_POST['textformat']; $_SESSION['font'] = $_POST['font']; $_SESSION['size'] = $_POST['size']; $_SESSION['color'] = $_POST['color']; ?> <html> <head> </head> <body> <p <?php echo ' style="font-family: ' . $_POST['font'] . '; '; echo 'font-size: ' . $_POST['size'] . '; '; echo 'color: ' . $_POST['color'] . '; '; ?> > <?php echo $_POST['textformat']; ?> </p> </body> </html> I'd like to use a text editor like this one: http://tinymce.moxiecode.com/examples/full.php for my forums. But I am not sure exactly how I would prevent abuse and injects to messed up the page, rather than being contained in the designated area it is meant for. Could some one please help me, I know htmlspecailchars will not work, since some of the code needs to render as html Im trying to figure out the best way to random a line from a text file and after the random delete that line from the file. This way the same username cannot be picked twice thanks for any input I’m trying to construct a button that simply writes an "aleph" character into a text area, see below.
My code does not work, can anyone tell me why ? How should I fix it ?
<!DOCTYPE html> <html> <meta charset="UTF-8"> <head> <title>Example</title> <script type="text/javascript"> //JavaScript code goes here function insertAtEnd(text) { var theArea = document.getElementById("thisArea"); theArea.value += '' + text + '';; } </script> </head> <body> <input type="button" id="aleph" name="aleph" value="Write an aleph" onClick="javascript:insertAtEnd(\'<span>א</span>\');return(false)" /> <textarea id="thisArea"> </textarea> </body> </html> I need some help...I want to read the contents of a file into a variable and then insert/write that content into another file. Code: [Select] $handle = fopen($create_mysql_db_url, "rb"); $contents = fread($handle, filesize($create_mysql_db_url)); fclose($handle); $userFileName = $_POST['mysqluser'] . time() . ".php.txt"; $fhandle = fopen($userFileName,"wb"); fwrite($fhandle, $contents); fclose($fhandle); $fh = fopen($userFileName,"wb"); $contents = fread($fh, filesize($userFileName)); $content = preg_replace("/###USERNAME###/", $_POST['mysqluser'], $contents); $content = preg_replace("/###PASSWORD###/", $_POST['mysqlpass'], $content); fwrite($fh, $content); fclose($fh); please help Hello friends, if i have the following $path = "http://*site*.com"; why can't i write the following $ORGtext= file_get_contents('$path'); it works only if i write $ORGtext= file_get_contents('http://*site*.com'); but i want to put $path instead of the url at file_get_contents is it possible and if yes then how ? thank you |