PHP - Get_file_contents Does Not Work With Existing Local Files
Hi.
I have php code that attempts to read a file into a string using get_file_contents(), but it claims the file does not exist. I do the same thing in another php file (same directory) and it works. Only difference is that the first file has the call in a function. File one: Code: [Select] $email_template = "../email_templates/new_instructor.html"; echo file_exists($email_template); $message = file_get_contents($email_template);//get the email template File two: Code: [Select] $email_template = "../email_templates/new_instructor.html"; echo file_exists($email_template); echo file_get_contents($email_file); please help.' thanx Similar TutorialsHey all, this is my first post ever and am not really sure if this is the right place for it or not, sorry in advance if it isn't. I'm new to PHP and trying to learn. I'm running Ubuntu 10.04 LTS and Firefox 3.6.22. I have libapache2-mod-php5 installed and running, but for some reason everytime I try to open a local .php file in firefox the download manager pops up and ask me what I want to do with the file. Has anyone else encountered this before? Is it something simple that I overlooked? Any help would be appreciated. I wrote this script to rename my many tv series I have on my pc, works by finding a string in the file name and replacing it
the script works fine until I want to replace the file name with something that is also in the path
file = band ep01.avi
path = j:\media\ TV shows\Band of Brothers\
so if I try to change "Band" to "Band of Brothers" the path changes as well
is there a way I can change the code so it dosent effect the path ??
<?php $path = 'J:\media\TV shows\Band of Brothers'; foreach(glob($path.'/*.*') as $filename){ echo $filename."</BR>"; } ?> <table align="center" width="200px" border="0" cellspacing="1" cellpadding="3"> <form name="form1" method="get" action="mov.php"> <tr> <td colspan="3"><strong> </strong></td> </tr> <tr> <td width="71">Replace</td> <td width="6">:</td> <td width="301"><input name="rep" type="text" id="rep"></td> </tr> <tr> <td>With</td> <td>:</td> <td><input name="with" type="text" id="with"></td> </tr> <tr> <tr> <td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td> </tr></form> </table> <?php if (isset($_GET["rep"])) { $rep1=$_GET['rep']; } if (isset($_GET["with"])) { $with1=$_GET['with']; } foreach(glob($path.'/*.*') as $filename){ $strip = str_replace($rep1, $with1, $filename); echo $strip."</br>"; rename($filename,$strip); } ?> Hi, ive recently created a gallery website and im happy with the way everything currently works. However the main drawback is the site uploads using a html webfom which is great for remote users or the odd image. However, as i want to mass upload my existing collection i will need the ability to read a selected folder and then to carry out all the same processes that existed from the existing html form upload. Im also using gdlibrary and checking file types to ensure they are within my allowed list, but im wondering if there are any other common security alerts i should be aware of to keep things a little bit safer if/when i publish outside of my LAN. So in a nut shell i need some assistance with changing my upload process to work for more than one file at a time, ideally by reading a folder, or at least reading X amount of files at a time - processing them then moving onto next batch of files in the list. Then the next part i need help with is checking/improving basic security of the system Is it possible to read from a file that is located on the user's local machine and not on the server? I have a CSV file that is about 70MB that I have to parse through and insert the data into a database. I have no problem doing this if I hard code the path to the file. Is there a way to get the path of the file that the user wants to be parsed into the database? I don't think uploading the file would be a good idea because, like I said, it is 70MB and is nearly 2 million lines. Simply parsing the file takes long enough without throwing in upload time.. Hello, I have a call tu function unserialize() in a script that receives a string and has to return an array. In my localhost it works properly but in the server it returns a 1 dimension array with empty value. I'm testing with the string a:1:{s:1:"0";s:8:"value_eq";} The php.ini configuration for magic_quotes is (in both, server and localhost): magic_quotes_gpc Off magic_quotes_runtime Off Other configurations is difficult to compare, as php info is long and very different in local and server. Any ideas where the problem might be? Thank you Hi guys, I need a help to find out what is a problem. Some of my code does not work on my local comp and in the same time it works well when I place it on Internet server. First example: Code: [Select] <body> <?php if($_POST['submit_form'] == "Submit") { $varNewTeam = $_POST['Reg_Team']; $varNewCity = $_POST['Reg_City']; $db = mysql_connect('localhost', 'root', '') or die ('no connection with server'); mysql_select_db('db_m ,$db) or die('DB error'); mysql_query ("INSERT INTO reg2012 VALUES ('$varNewTeam','$varNewCity')") or die('insert error'); } ?> <form action="registration_2012_form.php" method="post"> <p>Team: <input type="text" name="Reg_Team" size="20" maxlength="50" value="<?=$varNewTeam;?>" /><br /></p> <p>City: <input type="text" name="Reg_City" size="20" maxlength="50" value="<?=$varNewCity;?>" /><br /></p> <p><input type="Submit" value="Submit" name="submit_form" /></p> </form> </body> On local comp: It gives me message "Undefined index: submit_form". On Net server works well. If I split the code in two files. In the first one I leave the form with "action=FILE2.php" and put my php code in the second file "FILE2.php" - it starts work even on local server. second example: Code: [Select] <body> <?php $db = mysql_connect('localhost', 'root', '') or die ('no connection with server'); mysql_select_db('db_m' ,$db) or die('DB error'); mysql_query ("CREATE TABLE temp1 (team char(50), city char(50) )") or die('create tables error'); ?> </body> It works in the Net and can not create the TABLE on my local comp. I use XAMPP on my local comp (if it's important) So I'm reading a JSON, and I'm using the command GET_FILE_CONTENTS, and I'm getting results. However, the JSON is incomplete to a point where in some instances the variables/objects within do not always contain a certain array. Issue; I'm getting errors returned when that particular array does not exist. The code below is the line that's getting the error returned because the TAGS[0] doesn't exist in all instances. Question; How do I check if the array exists within the GET_FILE_CONTENTS object? See example; Code: [Select] If($dall->tags[0]->name==$catgrp) Error: Notice: Undefined offset: 0 in /var/www/vhosts/website/httpdocs/testjson/index.php on line 63 Notice: Trying to get property of non-object in /var/www/vhosts/website/httpdocs/testjson/index.php on line 63 I'm trying to create an online web editor. It works fine for opening and writing files on the same server where the web editor is hosted, but I want it to be able to get_file_contents, fopen and fwrite files on a remote server, logging in with ftp_connect and ftp_login. I've noticed the functions ftp_get and ftp_fget but I'd rather not create another local file, if possible I want to open the remote file directly into a <texarea> then save it directly back to the remote server. Is this possible? So far I just get errors... Here's an example of the code I'm trying to combine, to retrieve the contents of a file on a remote server and put them in a <textarea>: Code: [Select] <?php $conn = ftp_connect("ftp.domain.com"); ftp_login($conn, "username", "password"); ftp_pasv($conn, true); $filename='example.php'; // open file $fh = fopen($filename, "r") or die("Could not open file!"); // read file contents $datax = fread($fh, filesize($filename)) or die("Could not read file!"); $data=htmlspecialchars($datax); // close file fclose($fh); // close this connection ftp_close($conn); echo '<textarea cols="200%" rows="50">'.$data.'</textarea>'; ?> And another failed example: Code: [Select] <?php $filename='editor.php'; $fh = fopen("ftp://username:password@domain.com/example.php", "r") or die("Could not open file!"); $datax = fread($fh, filesize($filename)) or die("Could not read file!"); $data=htmlspecialchars($datax); fclose($fh); echo '<textarea cols="200%" rows="50">'.$data.'</textarea>'; ?> I got this script: But it give me error, file_get_contents cannot open stream. I need to add the FTP connection with user/pass paramaters. then look in set http url, to get the file contents(images) and transfer to ftp server location. Can Anyone take alook and tell me if I am going down the right path and how to get there. Please Code: [Select] function postToHost($host, $port, $path, $postdata = array(), $filedata = array()) { $data = ""; $boundary = "---------------------".substr(md5(rand(0,32000)),0,10); $fp = fsockopen($host, $port); fputs($fp, "POST $path HTTP/1.0\n"); fputs($fp, "Host: $host\n"); fputs($fp, "Content-type: multipart/form-data; boundary=".$boundary."\n"); // Ab dieser Stelle sammeln wir erstmal alle Daten in einem String // Sammeln der POST Daten foreach($postdata as $key => $val){ $data .= "--$boundary\n"; $data .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n"; } // Sammeln der FILE Daten if($filedata) { $data .= "--$boundary\n"; $data .= "Content-Disposition: form-data; name=\"".$filedata['name']."\"; filename=\"".$filedata['name']."\"\n"; $data .= "Content-Type: ".$filedata['type']."\n"; $data .= "Content-Transfer-Encoding: binary\n\n"; $data .= $filedata['data']."\n"; $data .= "--$boundary--\n"; } // Senden aller Informationen fputs($fp, "Content-length: ".strlen($data)."\n\n"); fputs($fp, $data); // Auslesen der Antwort while(!feof($fp)) { $res .= fread($fp, 1); } fclose($fp); return $res; } $postdata = array('var1'=>'today', 'var2'=>'yesterday'); $filedata = array( 'type' => 'image/png', 'data' => file_get_contents('http://xxx/tdr-images/images/mapping/dynamic/deals/spot_map') ); echo '<pre>'.postToHost ("localhost", 80, "/test3.php", $postdata, $filedata).'</pre>'; Hi i have the script to upload files i set the type of file and extension allowed all the files type and extension i can upload except mp4 is ther anything extra i need to do isnt file type (video/mp4) extension (mp4) but still not working. Code: [Select] <?php mysql_connect("localhost", "root", "") or die(mysql_error()) ; mysql_select_db("database_name") or die(mysql_error()) ; // my file the name of the input area on the form type is the extension of the file //echo $_FILES["myfile"]["type"]; //myfile is the name of the input area on the form $name = $_FILES["image"]["name"]; // name of the file $type = $_FILES["image"]["type"]; //type of the file $size = $_FILES["image"]["size"]; //the size of the file $temp = $_FILES["image"]["tmp_name"];//temporary file location when click upload it temporary stores on the computer and gives it a temporary name $error =array(); // this an empty array where you can then call on all of the error messages $allowed_exts = array('jpg', 'jpeg', 'png', 'gif','avi','mp4'); // array with the following extension name values $image_type = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif', 'video/mp4'); // array with the following image type values $location = 'images/'; //location of the file or directory where the file will be stored $appendic_name = "news".$name;//this append the word [news] before the name so the image would be news[nameofimage].gif // substr counts the number of carachters and then you the specify how how many you letters you want to cut off from the beginning of the word example drivers.jpg it would cut off dri, and would display vers.jpg //echo $extension = substr($name, 3); //using both substr and strpos, strpos it will delete anything before the dot in this case it finds the dot on the $name file deletes and + 1 says read after the last letter you delete because you want to display the letters after the dot. if remove the +1 it will display .gif which what we want is just gif $extension = strtolower(substr($name, strpos ($name, '.') +1));//strlower turn the extension non capital in case extension is capital example JPG will strtolower will make jpg // another way of doing is with explode // $image_ext strtolower(end(explode('.',$name))); will explode from where you want in this case from the dot adn end will display from the end after the explode $title = $_POST["title"]; $subtitle = $_POST["subtitle"]; if (isset($image)) // if you choose a file name do the if bellow { // if extension is not equal to any of the variables in the array $allowed_exts error appears if(in_array($extension, $allowed_exts) === false ) { $error[] = 'Extension not allowed! gif, jpg, jpeg, png only<br />'; // if no errror read next if line } // if file type is not equal to any of the variables in array $image_type error appears if(in_array($type, $image_type) === false) { $error[] = 'Type of file not allowed! only images allowed<br />'; } // check if folder exist in the server if(!file_exists ($location)) { $error[] = 'No directory ' . $location. ' on the server Please create a folder ' .$location; } } // if no error found do the move upload function if (empty($error)){ if (move_uploaded_file($temp, $location .$appendic_name)) { if (move_uploaded_file($temp1, $location .$name1)) { // insert data into database first are the field name teh values are the variables you want to insert into those fields appendic is the new name of the image mysql_query("INSERT INTO tablename (title, subtitle, image) VALUES ('$title', '$subtitle', '$appendic_name')") ; echo $type; echo "<br />"; echo $type1; } } else { foreach ($error as $error) { echo $error; } } } //echo $type; ?> I am developing a database app for a client who needs to import hundreds of thousands of codes into the DB to check against. The codes are in 4 text files about 30MB each. The codes are 3 per line, then a line break, and 3 more. Ive written a script to parse out the line breaks, turn the data into an array, then loop over thay array and insert into the DB. The problem is these scripts take minutes to run using file_get_contents and by the time the data is ready the mmysql connection is gone. Plus even these files only work after Ive cut the files into about 1MB each, so each file is 30 smaller ones. Is there a way to just put the text file on the server, and have php search it using a GREP like function that won't be such a burden to work with. Any advice helps. James Hello I have a simple question about file handling... Is it possible to list all files in directories / subdirectories, and then read ALL files in those dirs, and put the content of their file into an array? Like this: array: [SomePath/test.php] = "All In this php file is being read by a new smart function!"; [SomePath/Weird/hello.txt = "Hello world. This is me and im just trying to get some help!";and so on, until no further files exists in that rootdir. All my attempts went totally crazy and none of them works... therefore i need to ask you for help. Do you have any ideas how to do this? If so, how can I be able to do it? Thanks in Advance, pros So far I have managed to create an upload process which uploads a picture, updates the database on file location and then tries to upload the db a 2nd time to update the Thumbnails file location (i tried updating the thumbnails location in one go and for some reason this causes failure) But the main problem is that it doesn't upload some files Here is my upload.php <?php include 'dbconnect.php'; $statusMsg = ''; $Title = $conn -> real_escape_string($_POST['Title']) ; $BodyText = $conn -> real_escape_string($_POST['ThreadBody']) ; // File upload path $targetDir = "upload/"; $fileName = basename($_FILES["file"]["name"]); $targetFilePath = $targetDir . $fileName; $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); $Thumbnail = "upload/Thumbnails/'$fileName'"; if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){ // Allow certain file formats $allowTypes = array('jpg','png','jpeg','gif','pdf', "webm", "mp4"); if(in_array($fileType, $allowTypes)){ // Upload file to server if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ // Insert image file name into database $insert = $conn->query("INSERT into Threads (Title, ThreadBody, filename) VALUES ('$Title', '$BodyText', '$fileName')"); if($insert){ $statusMsg = "The file ".$fileName. " has been uploaded successfully."; $targetFilePathArg = escapeshellarg($targetFilePath); $output=null; $retval=null; //exec("convert $targetFilePathArg -resize 300x200 ./upload/Thumbnails/'$fileName'", $output, $retval); exec("convert $targetFilePathArg -resize 200x200 $Thumbnail", $output, $retval); echo "REturned with status $retval and output:\n" ; if ($retval == null) { echo "Retval is null\n" ; echo "Thumbnail equals $Thumbnail\n" ; } }else{ $statusMsg = "File upload failed, please try again."; } }else{ $statusMsg = "Sorry, there was an error uploading your file."; } }else{ $statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, mp4, webm & PDF files are allowed to upload.'; } }else{ $statusMsg = 'Please select a file to upload.'; } //Update SQL db by setting the thumbnail column to equal $Thumbnail $update = $conn->query("update Threads set thumbnail = '$Thumbnail' where filename = '$fileName'"); if($update){ $statusMsg = "Updated the thumbnail to sql correctly."; echo $statusMsg ; } else { echo "\n Failed to update Thumbnail. Thumbnail equals $Thumbnail" ; } // Display status message echo $statusMsg; ?> And this does work on most files however it is not working on a 9.9mb png fileĀ which is named "test.png" I tested on another 3.3 mb gif file and that failed too? For some reason it returns the following Updated the thumbnail to sql correctly.Updated the thumbnail to sql correctly. Whereas on the files it works on it returns REturned with status 0 and output: Retval is null Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif' Failed to update Thumbnail. Thumbnail equals upload/Thumbnails/'rainbow-trh-stache.gif'The file rainbow-trh-stache.gif has been uploaded successfully. Any idea on why this is? I am using WPSQT plugin in my blog site .I code some files in PHP also.how to add that files in plugin files.
I spent some time "Googling" today but all I found was how to create PDFs on the fly. What I wonder is if it is possible to print text on an existing PDF. And if so, could I get some pointer where to obtain this knowledge? Simply put. I have a PDF form that is not yet filled out. I would like to be able to look up an address and other information in a database, and use that information to print on the existing PDF file. Any help is much appreciated. Is there a way to instantiate a PDO object using an already existing database connection? Or does PDO detect an already opened connection and use it? The existing connection is a persistant connection. Can anyone help me please, I am trying to place a PHP calendar into an existing DIV tag that used to hold a flash slideshow application, but we want to replace that with a calendar. Here is my code: Code: [Select] echo '<div class="grid_9"> <div class="box"> <h2>'.$titleone.'</h2> <div class="block">'; if (!defined('BLOCK_FILE')) { Header('Location: ../index.php'); die(); } $modName = 'GCalendar'; $blockConfig = array('maxTitle' => 21, 'eventPrefix' => '• ', 'maxEvents' => 10, 'lookahead' => 2, 'twoColumn' => false, 'excludeCats' => array(), 'force_center' => false, ); require_once 'modules/' . $modName . '/language.php'; gcalGetLang($modName); require_once 'modules/' . $modName . '/gcal.inc.php'; require_once 'modules/' . $modName . '/common.inc.php'; require_once 'modules/' . $modName . '/getMonthlyEvents.php'; require_once 'modules/' . $modName . '/gcalBlock.php'; $config = getConfig(); list($year, $month, $today) = explode(',', date('Y,n,j')); $block = new GCalBlock($year, $month, $today, $config, $blockConfig); $content = $block->calendar(); $content .= '<br />'; $content .= $block->upcomingEvents(); echo '</div> </div> </div>'; When I try this above, I just get an 'Too many page loads' error, so I'm not sure what I've done wrong. Any help appreciated. Regards, Tree I would like to support UTF-8 on my website but am unsure - and quite fearful - whether it will break my existing code or not?! I looked at http://us3.php.net/mbstring(), but worry that I'm going to miss something. Here is some sample code where I think things could easily break... // Trim all Form data. $trimmed = array_map('trim', $_POST); // ************************ // Validate Form Data. * // ************************ // Validate First Name. if (empty($trimmed['firstName'])){ // No First Name. $errors['firstName'] = 'Enter your First Name.'; }else{ // First Name Exists. if (preg_match('#^[A-Z \'.-]{2,30}$#i', $trimmed['firstName'])){ // Valid First Name. $firstName = $trimmed['firstName']; }else{ // Invalid First Name. $errors['firstName'] = 'First Name must be 2-30 characters (A-Z \' . -)'; } }//End of VALIDATE FIRST NAME // Validate Username. if (empty($trimmed['username'])){ // No Username. $errors['username'] = 'Enter your Username.'; }else{ // Username Exists. if (preg_match('~(?x) # Comments Mode ^ # Beginning of String Anchor (?=.{8,30}$) # Ensure Length is 8-30 Characters .* # Match Anything $ # End of String Anchor ~i', $trimmed['username'])){ // Valid Username. // ****************************** // Check Username Availability. * // ****************************** // Build query. $q1 = 'SELECT id FROM member WHERE username=?'; // Prepare statement. $stmt1 = mysqli_prepare($dbc, $q1); // Bind variable to query. mysqli_stmt_bind_param($stmt1, 's', $trimmed['username']); // Execute query. mysqli_stmt_execute($stmt1); // Store results. mysqli_stmt_store_result($stmt1); // Check # of Records Returned. if (mysqli_stmt_num_rows($stmt1)>0){ // Duplicate Username. $errors['username'] = 'This Username is taken. Try again.'; }else{ // Unique Username. $username = $trimmed['username']; } }else{ // Invalid Username. $errors['username'] = 'Username must be 8-30 characters.'; } }//End of VALIDATE USERNAME Three possible areas where I could run into trouble are with... 1.) array_map 2.) preg_match 3.) Prepared Statements For #2, I see there is mb_ereg_match but I am not sure if I just replace my current Regex function with that one, or if there is more involved. I'm not sure if any problems would arise with #1 or #3 or elsewhere, and would really appreciate a second set of eyes on this code!! requinix said switching is a good idea, but I'm pretty freaked out that I'm going to break things and create a big security hole?! Any help would be appreciated!! Thanks, Debbie Okay so I have a time in the format yyyy-mm-dd that is pulled from a MySQL array row and I need to add one month to it then echo that out. I assume it has something to do with the strtotime() and date() functions but I have tried every combination and cannot figure it out. Can I get some assistance please and thank you? Very very very new to php. Here is what I have lol; Code: [Select] $row=mysql_fetch_array($result); $ddaterow=$row['donation_date']; Like I said the date will always be in the format yyyy-mm-dd |