I have some questions about fopen
The first question it’s when i go for add new entry always put to the end of file and no start the file, for example:
$fp=fopen("text.dat","a");
fputs($fp,"Hello 1"."\n");
fclose($fp);
Always the results in this file show to the end:
Hello 1
Hello 2
Hello 3
And no as I want, insert the new comment to the first place for show this as:
Hello 3
Hello 2
Hello 1 ( The most old entry )
By other side my second question, for example if i have 10 users and this 10 users to the same time insert one entry or post inside this text file, it’s possible or can give me some error? Or I need use flock until save each post, which it’s the best method for no give me problems when some users want change something in the file in the same time?
There's no way to prepend the file automatically. So, it is better to store the existing contents in a temp file and then insert it in the file.
$fp=fopen("text.dat","w");
fwrite($fp,"Hello 1"."\n".fread($fp));
fclose($fp);
This will be outputting as:
Hello 3
Hello 2
Hello 1
But as far as lock is considered, I don't think it is possible, or am not the right person to answer for this.
When you write to a file it'll always append at the end. There's no workaround it which I'm aware of, but in order to achieve what you want (which is to display the lines in reverse order) you can read the lines into an array and display the array in reverse order.
As for locking, only one process can hold the lock to a file, so you don't really have to do anything cause if two users try to update the same file at the same time - only one of them will succeed - which actually creates a different problem (one of the users will lose her post). In order to work around it you should send to the backend both the original copy of the post and the new version submitted by the user, before you save the user's edit - check that the original version is updated. If it's not up-to-date it means that another user changed it meanwhile. The "user-friendly" behavior would be to return an error to the user saying that he's version is not up-to-date but also include his edits - so that he won't have to re-write everything from scratch.
For that you need a database, which is more suited for multi-user things and sorting,
Or else use a subdirectory and create every message in its own file, with a file name made up of a sortable timestamp: yyyymmddhhmmss. But then you need to prevent directory caching.
As everyone has the right to be stubborn/cut of an edge: see file_get_contents to load all the contents, and file_put_contents.
Related
I need help parsing the following a CSV file in PHP, so I can insert the contents into a database.
I know I use file_get_contents() but after that I feel a bit lost.
What I'd like to store.
Collection1 - events.text & date
Collection2 - position & name.text & total
I'm not sure how best structure the data to insert into a database table.
"**collection1**"
"events.href","**events.text**","**date**","index","url"
"tur.com/events/classic.html","John Deere Classic","Thursday Jul 9
- Sunday Jul 12, 2015","1","tur.com/r.html"
"collection2"
"**position**","name.href","**name.text**","**total**","index","url"
"--","javascript:void(0);","Scott","--","2","tur.com/r.html"
"--","javascript:void(0);","Billy","--","3","tur.com/r.html"
"--","javascript:void(0);","Jon","--","4","tur.com/r.html"
"--","javascript:void(0);","Bill","--","5","tur.com/r.html"
"--","javascript:void(0);","Tim","--","6","tur.com/r.html"
"--","javascript:void(0);","Carlos","--","7","tur.com/r.html"
"--","javascript:void(0);","Robert","--","8","tur.com/r.html"
"--","javascript:void(0);","Rod","--","9","tur.com/r.html"
As per your previous question, I think this needs to be broken down into sections. As it stands it is rather too broad to answer.
Read the information using file_get_contents(). Make sure this works first, by echoing it to the console. (It sounded from your other question that you felt this would not work if the URL does not have a .csv suffix. It should work regardless of the file extension - try it. If it fails it may be dependent on cookies or JavaScript or some other problem).
Design and create your table structure in MySQL. It seems like you have two tables. They should both have a primary key. Are they related in some fashion? If so, perhaps one has a foreign key to the other one?
Explode your text file on the new line character and loop across the resulting array of lines.
If your CSV data has a title row in the first row position, delete that from your array.
For each line, read the elements of interest using PHP's build-in CSV parsing functions, and store them in variables.
Pass these variables to a custom function that saves the data.
For each save, you'll need to do an INSERT. I recommend using PDO here. Make sure you bind your parameters.
Where you get stuck on a specific problem, you can ask a new and focussed question. At present, the task is to break things down into discrete and researchable pieces.
One trick worth remembering is this shortcut to the PHP manual. If you do not know how fgetcsv works, for example, type php.net/fgetcsv into your browser address bar, and the PHP site will find the function for you. The documentation is excellent.
There are quite a few different threads about this similar topic, yet I have not been able to fully comprehend a solution to my problem.
What I'd like to do is quite simple, I have a flat-file db, with data stored like this -
$username:$worldLocation:$resources
The issue is I would like to have a submit data html page that would update this line based upon a search of the term using php
search db for - $worldLocation
if $worldLocation found
replace entire line with $username:$worldLocation:$updatedResources
I know there should be a fairly easy way to get this done but I am unable to figure it out at the moment, I will keep trying as this post is up but if you know a way that I could use I would greatly appreciate the help.
Thank you
I always loved c, and functions that came into php from c.
Check out fscanf and fprintf.
These will make your life easier while reading writing in a format. Like say:
$filehandle = fopen("file.txt", "c");
while($values = fscanf($filehandle, "%s\t%s\t%s\n")){
list($a, $b, $c) = $values;
// do something with a,b,c
}
Also, there is no performance workaround for avoiding reading the entire file into memory -> changing one line -> writing the entire file. You have to do it.
This is as efficient as you can get. Because you most probably using native c code since I read some where that php just wraps c's functions in these cases.
You like the hard way so be it....
Make each line the same length. Add space, tab, capital X etc to fill in the blanks
When you want to replace the line, find it and as each line is of a fixed length you can replace it.
For speed and less hassle use a database (even SQLLite)
If you're committed to the flat file, the simplest thing is iterating through each line, writing a new file & changing the one that matches.
Yeah, it sucks.
I'd strongly recommend switching over to a 'proper' database. If you're concerned about resources or the complexity of running a server, you can look into SQLite or Berkeley DB. Both of these use a database that is 'just a file', removing the issue of installing and maintaining a DB server, but still you the ability to quickly & easily search, replace and delete individual records. If you still need the flat file for some other reason, you can easily write some import/export routines.
Another interesting possibility, if you want to be creative, would be to look at your filesystem as a database. Give each user a directory. In each directory, have a file for locations. In each file, update the resources. This means that, to insert a row, you just write to a new file. To update a file, you just rewrite a single file. Deleting a user is just nuking a directory. Sure, there's a bit more overhead in slurping the whole thing into memory.
Other ways of solving the problem might be to make your flat-file write-only, since appending to the end of a file is a trivial operation. You then create a second file that lists "dead" line numbers that should be ignored when reading the flat file. Similarly, you could easily "X" out the existing lines (which, again, is far easier than trying to update lines in a file that might not be the same length) and append your new data to the end.
Those second two ideas aren't really meant to be practical solutions as much as they are to show you that there's always more than one way to solve a problem.
ok.... after a few hours work..this example woorked fine for me...
I intended to code an editing tool...and use it for password update..and it did the
trick!
Not only does this page send and email to user (sorry...address harcoded to avoid
posting aditional code) with new password...but it also edits entry for thew user
and re-writes all file info in new file...
when done, it obviously swaps filenames, storing old file as usuarios_old.txt.
grab the code here (sorry stackoverflow got VERY picky about code posting)
https://www.iot-argentina.xyz/edit_flat_databse.txt
Is that what you are location for :
update `field` from `table` set `field to replace` = '$username:$worldlocation:$updatesResources' where `field` = '$worldLocation';
I want to create a very simple site, but unfortunately my php skills are weak. Basically, when a user shows up, I want to have a page with text and a blinking cursor (I can probably figure the cursor part out myself, but feel free to suggest). When a user types, I want it to show the text as they type, and when they hit enter (or click something/whatever), the text just typed will be sent to a database and then the page will update with that new text, for anybody else to see. The cursor will then be blinking on the next line down. So basically it's like a really simple wiki, where anyone can add anything, but nobody can ever remove what has been typed before. No logging in or anything. Can someone suggest the best way to go about this? I assume it will require a php call to the database to display the initial page, then another php request to send data, then another php request to display the new page. I just don't know the details. Thanks so much!
Bonus question 1: How can the page be updated dynamically, so if A sends text while B is typing, B sees the text A sent on B's page immediately?
Bonus question 2: What sorts of issues might arise if this database grows extremely large (say, millions of words), and how might I address these up front? If necessary, I could show only a small chunk of the (text-only) database on any given page, then have pagination.
If you only have one page, you don't need a database. All you need to do is save a text file on the server (use fopen() and related functions) that only gets appended to. If you have multiple pages, then a simple id (INTEGER), filetext (LARGEBLOB). (Note largeblob has a limit of 2^32 bytes).
For the user's browser part, you'll need to use Javascript and AJAX to inform the server of any updates. Just get in touch with a PHP script that (1) accepts the input and (2) appends it to a file.
Bonus question 1: How can the page be updated dynamically, so if A sends text while B is typing, B sees the text A sent on B's page immediately?
Also use the AJAX call to fetch new content (e.g. if you assign line numbers, then the browser just tells the script the last line it read, and the script returns all new lines past that point).
I assume it will require a php call to the database to display the initial page, then another php request to send data, then another php request to display the new page.
Pretty much. But only send the last 50 lines or so of the file when the browser visits it. You don't want to crash the browser.
Bonus question 2: What sorts of issues might arise if this database grows extremely large (say, millions of words), and how might I address these up front? If necessary, I could show only a small chunk of the (text-only) database on any given page, then have pagination.
Think in terms of bytes, not words, and you'll likely run into performance issues. You could cap file sizes or split up the storage into multiple files at a certain size so you don't have to scan pass content that will rarely be fetched.
I'm designing a website for a small indie record label and they've dropped a bombshell asking if I could implement a function where a user can enter a code to receive a digital download.
Is there a simple solution to doing this? I was thinking all I would need is an input field where the user can enter a code, it gets verified and then allows a download but it sounds too simple. Is this even possible with something like .php (complete beginner)?
I'm willing to learn or I would've packed it in already so any advice would be great. Thanks.
Edit:
Thanks to some great advice I was able to create this!
If you wanted to do it at a very simple level, it is not much more than you describe it to be. You would need to familiarize with PHP and MySQL or some other database, but it isn't too difficult to create.
You need to figure a few things out, such as how do you want to limit the codes, 3 downloads in the first 24 hours to allow for failed downloads, restrict it to IP, or strictly one full download. Since you have the list of the 1000 codes given, you will probably want to base your system around having codes pre-generated and inserted in the database, rather than having an algorithm that can validate the codes on the fly and then check for already used codes.
You would want to store the download(s) in a directory that is not accessible from the web, and the php script would validate the code, and if valid serve the download to the user.
You can probably look to the wordpress plugin's database structure for other ideas, but I think at the very least you would need:
download_code (the code itself, probably primary key or at least index)
download_file (optional, the name/path of the file this code allows them to download)
redeemed (0 if not redeemed, 1 if redeemed)
redemption_time (timestamp of the first, or last redemption based on your requirements)
download_count (how many times downloaded if allowing more than 1)
ip_address (ip address of the redeemer)
email_address (email address if you want to collect it, or give user the option)
download_url (the unique string for the download url. this could be one way to implement download verification beyond the code, but is not necessary)
You would then need to create an html page with the text box for entering the code, and any other optional data you wish to collect. The form would submit to your PHP script.
When the PHP script receives a form post, it would validate all of the data (i.e. email address if you were collecting it). Once all data is valid, you read from the database looking for a code matching what the user entered.
If no data was found with the code, send them back to the form to try re-entering it. If a record is found, you can check the redeemed value from the database and see if the code has been used or not. If it has, this is where you can use custom logic to decide if they are still within their download window, the ip address is the same, or whatever criteria you want to use to allow re-downloads.
If it has been redeemed, show an error message. If it is still okay to download, you can serve a download by reading the file and sending it to the browser see example #1 here.
At some point you will have to update your database to set the redeemed flag to 1 and update the other values such as timestamp and download count. You can either run this code before you serve the download, or you can run it after the download is served. In some cases if the download was cut off, the last portion of your script won't run and therefore won't update redeemed or download_count. This may or may not be what you want, so you can decide where you want to do the updating.
Eventually you can update it to include an administration panel, but in the beginning all configuration could be done within the php script or config file. And eventually you could update it to use flash or some other technology to download the file and show progress bars etc.
Hopefully that will give you some idea on whether or not you want to try to implement it. Otherwise you could always search php on Hotscripts to see if there is an already rolled standalone version of what you want.
I want to get content of a textbox posted on other page without database, means m creating a complaint box, and complaint should be posted on admin page. Every new complain should b at top and others below it. can you please help.
When you store some data, you are creating Data-Base as well
If you don't want to use SQL or similar (liteSQL, XML file DB,...)
you can use directory structure like this
/[year]
/[year]/[month]
/[year]/[month]/[day]
/[year]/[month]/[day]/[exact_timestamp]+[random_hash].[file_extension]
and save them in file structure, each complain as standalone text file
It may be best to just have one, delimited file. Then you only have to read from one place. Depending on the frequency of your complaints, you may want to have one file per day.
To avoid strange locking issues maybe do something similar to what Marek suggested and temporarily store each complaint in a standalone file. Then run a CRON to concatenate them every so often